答案 0 :(得分:1)
尝试使用&&而不是||像这样:
} while (!isNumber && !isNumPos);
答案 1 :(得分:1)
我想知道这会更容易吗? :)
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int numberOne = 0;
int numberTwo = 0;
boolean flag = true;
System.out.println("Enter a positive number: ");
numberOne = input.nextInt();
System.out.println("Enter another positive number: ");
numberTwo = input.nextInt();
while (flag) {
if (numberOne > 0 && numberTwo > 0) {
flag = false;
} else if (numberOne <= 0) {
System.out.println("First number was invalid, please enter a positive number: ");
numberOne = input.nextInt();
flag = true;
} else if (numberTwo <= 0) {
System.out.println("Second number was invalid, please enter a positive number: ");
numberTwo = input.nextInt();
flag = true;
}
}
System.out.println("Your numbers were " + numberOne + " and " + numberTwo);
}
答案 2 :(得分:0)
我稍稍调整了你的代码。但是,有更简单的方法可以做到这一点。
do {
System.out.print("Enter a positive integer: ");
firstN = input.nextInt();
isNumber = true;
if (firstN > 0) {
isNumPos = true;
isNumber = true;
break;
} else {
isNumPos = false;
isNumber = false;
continue;
}
} while (!(isNumber) || !(isNumPos));
do {
System.out.print("Enter another positive integer: ");
secondN = input.nextInt();
isNumber = true;
if (secondN > 0) {
isNumPos = true;
isNumber = true;
} else {
isNumPos = false;
isNumber = false;
}
} while (!(isNumber) || !(isNumPos));