英文:
How can have the while loop working properly?
问题
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;
}
英文:
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;
}
答案1
得分: 0
如果像billjamesdev建议的那样,目的是让用户输入一个非负整数,那么代码可以变得更简单。
不需要使用-8的那些奇技淫巧,
public static int userInput() {
Scanner scanner = new Scanner(System.in);
int enteredValue = -8; // 仅用于启动循环
while (enteredValue < 0) {
try {
enteredValue = scanner.nextInt();
if (enteredValue < 0)
System.out.println("输入了负整数");
}
catch (InputMismatchException ex) {
System.out.println("输入了无效的整数");
scanner.nextLine(); // 清除输入
}
}
scanner.nextLine();
return enteredValue;
}
注意:与其在负数输入时抛出异常,我选择直接报告错误,因为这使我能够使用更具体的消息。
一个微妙之处在于,如果抛出了异常,那么enteredValue
上就不会发生赋值,因此它仍然是负数,因为它与循环顶部的值保持不变。
使用do-while循环似乎并没有在可读性方面增加太多好处,所以我将其保留为while循环。
英文:
If, as billjamesdev suggests, the point is to get the user to enter a non-negative integer, the code can be made simpler.
None of that magic with -8 is needed, and
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;
}
Note: rather than throwing an exception on negative input, I chose to just report the error directly, since this allows me to use a more specific message.
A subtlety is that if the exception is thrown, then no assignment to enteredValue
can have occurred, and therefore it is still negative, since it is unchanged from the top of the loop.
Using a do-while loop didn't seem to add much to readability, so I left it as a while-loop.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论