Java 如何使while循环正常工作?
如果像billjamesdev所建议的那样,关键是让用户输入一个非负整数,那么代码可以变得更简单 不需要-8的魔法,而且Java 如何使while循环正常工作?,java,Java,如果像billjamesdev所建议的那样,关键是让用户输入一个非负整数,那么代码可以变得更简单 不需要-8的魔法,而且 public static int userInput() { Scanner scanner = new Scanner(System.in); int enteredValue = -8; while (enteredValue !=8) { try { enteredValue = scanner.nex
public static int userInput() {
Scanner scanner = new Scanner(System.in);
int enteredValue = -8;
while (enteredValue !=8) {
try {
enteredValue = scanner.nextInt();
if (enteredValue < 0) {
throw new InputMismatchException();
}
} catch (InputMismatchException e) {
System.out.println("Invalid interger entered");
enteredValue = -8;
}
break;
}
scanner.nextLine();
return enteredValue;
}
注意:我选择直接报告错误,而不是对负输入抛出异常,因为这允许我使用更具体的消息
微妙之处在于,如果抛出异常,则不会发生对enteredValue的赋值,因此它仍然是负数,因为它从循环的顶部开始保持不变
使用do while循环似乎并没有增加多少可读性,所以我将其作为while循环使用。当我不写break时,它将继续提供无限循环这段代码的意图是什么?循环应该什么时候结束?现在,没有中断,它将一直询问,直到用户输入8。有了中断,它将永远不会循环,因此您最好不要循环。也许您的意思是,虽然enteredValue==-8,但它最初进入循环,如果捕获到异常,它将继续循环。@CaiusJard,如果enteredValue<0,则返回-8;否则,由于break@fatunkazi只需添加scanner.next;在catch块中,你有无限循环,因为无效值不是整数,仍然在输入缓冲区中,你无法读取它。现在只需输入类似字符串asd的内容,你就会得到无限循环。是的,在你上面提到它之后,我看到了-谢谢。
public static int userInput() {
Scanner scanner = new Scanner(System.in);
int enteredValue = -8; // just to get loop started
while (enteredValue < 0) {
try {
enteredValue = scanner.nextInt();
if (enteredValue < 0)
System.out.println("Negative integer entered");
}
catch (InputMismatchException ex) {
System.out.println("Invalid integer entered");
scanner.nextLine(); // clear input
}
}
scanner.nextLine();
return enteredValue;
}