gpt4 book ai didi

java - int 值的验证

转载 作者:行者123 更新时间:2023-12-01 09:18:11 24 4
gpt4 key购买 nike

我试图打印一条消息说“错误”,然后每次用户输入非 int 的内容时都有机会输入该值。

我有以下代码:

do {

System.out.println("Enter last name: ");
lastName = input.next();

System.out.println("Enter first name: ");
firstName = input.next();

do {
System.out.println("Enter exam 1 score: ");
if (input.hasNextInt()) {
ex1 = input.nextInt();

System.out.println("Enter exam 2 score: ");
ex2 = input.nextInt();

System.out.println("Enter exam 3 score: ");
ex3 = input.nextInt();

valid = true;

} else {
System.out.println("Incorrect choice. Write the score in numbers." + "\n");
valid = false;
input.next(); // Prevents infinite loop
}
} while (!valid);

只有当用户在考试 1 中犯错时,这似乎才能正常工作,但如果他们在考试 2 或 3 中犯了错误,就会出现错误。

非常感谢您的帮助。

最佳答案

尽量不要一次又一次地编写相同的代码。使用循环。

final int MAX_SCORES = 3;

while (true) {
System.out.println("Enter last name: ");
String lastName = input.next();

System.out.println("Enter first name: ");
String firstName = input.next();

int scores = new int[MAX_SCORES];
for (int i = 0; i < MAX_SCORES; ) {
System.out.printf("Enter exam %d score: ", i + 1);
if (input.hasNextInt()) {
scores[i++] = input.nextInt(); // increment 'i' after assignment
} else {
System.out.println("Incorrect choice. Write the score in numbers.\n");
// Loop will repeat at same value of 'i'
}
}

System.out.println("Again? (Y/N)");
if (input.next().equalsIgnoreCase("n")) break; // Prevents infinite loop
}

关于java - int 值的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40369133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com