我遇到问题。代码应该采用两位数字,其中数字不同。如果它不是整数,则代码会告诉您并要求重新输入。如果它是整数但不符合条件,它会告诉你,然后提示重新输入。除了当您输入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。试试吧,它会高度简化问题。 –