我遇到問題。代碼應該採用兩位數字,其中數字不同。如果它不是整數,則代碼會告訴您並要求重新輸入。如果它是整數但不符合條件,它會告訴你,然後提示重新輸入。除了當您輸入0來結束循環/程序時,所有內容都可以使用。我已經堅持了2天。有什麼建議麼?範圍和輸入類型驗證
int num = 1;
while (num != 0) {
System.out.print("Enter a 2-digit number. The digits should be different. Zero to stop: ");
while (!in.hasNextInt()) {
System.out.print("Not an integer, try again: ");
in.next();
}
num = in.nextInt();
while (num < 10 || num > 99) {
System.out.println("NOT good for your game!");
System.out.print("Enter a 2-digit number. The digits should be different. Zero to stop: ");
while (!in.hasNextInt()) {
System.out.print("Not an integer, try again: ");
in.next();
}
num = in.nextInt();
}
if (equalDigs(num) == false)
System.out.println("NOT good for you game!");
else
System.out.println("Good for your game! Play!");
}
}
public static boolean equalDigs(int n) {
int d1 = n/10;
int d2 = n % 10;
if (d1 == d2)
return false;
else
return true;
}
您應該對此用例使用do-while。試試吧,它會高度簡化問題。 –