3
當您連續兩次輸入一個'i'等隨機值時,程序終止。我想這樣做,所以「無效的數據請再試一次」,然後「你想再玩一次」繼續重複,直到輸入N或Y.當連續輸入錯誤時,循環中斷java
7 8 5
No numbers match
Do you want to play again?
i
Invalid data please try again
Do you want to play again?
i
Thank you for using this program
它應該是:
7 8 5
No numbers match
Do you want to play again?
i
Invalid data please try again
Do you want to play again?
i
Invalid data please try again
Do you want to play again?
...等等。
代碼:
import java.util.Random;
import java.util.Scanner;
public class TestSlotMachine {
public static void main(String[] args) {
String choice;
Scanner keyboardScanner = new Scanner(System.in);
do {
Random randomNumber = new Random();
int slot1, slot2, slot3;
slot1 = randomNumber.nextInt(9);
slot2 = randomNumber.nextInt(9);
slot3 = randomNumber.nextInt(9);
System.out.println(slot1+" "+slot2+" "+ slot3);
if (slot1 != slot2 && slot1 != slot3 && slot2 != slot3) {
System.out.println("No numbers match");
}
else if (slot1 == slot2 && slot2 == slot3) {
System.out.println("Three numbers match");
}
else {
System.out.println("Two numbers match");
}
System.out.println("Do you want to play again?");
choice = keyboardScanner.next();
if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")) {
System.out.println("Invalid data please try again");
System.out.println("Do you want to play again?");
choice = keyboardScanner.next();
}
} while (choice.equalsIgnoreCase("y"));
System.out.println("Thank you for using this program");
keyboardScanner.close();
}
}
它不應該是||代替 &&? –
@CodingEnthusiast不,因爲那樣會永遠是真的。 – Kayaman
哦,我的壞。剛剛意識到。謝謝 –