gpt4 book ai didi

java - java 如何退出for循环?

转载 作者:行者123 更新时间:2023-11-30 06:23:08 28 4
gpt4 key购买 nike

嗨,我正在编写java代码,它将接受用户输入并将用户输入放入ArrayList中,但我希望用户在输入所有数据后能够输入Q。但是当我在某些情况下输入 q 时,我得到了错误的输出。

public void enterScores() 
{
System.out.println("Enter the scores of the student, press Q to finish");
for (int i = 0; i < SCORES_SIZE; i++)
{
exitLoop = userInput.next();
if (exitLoop.equalsIgnoreCase("Q"))
{
break;
}
scores.add(i, userInput.nextInt());
}
System.out.println("___________");
for (int i = 0; i < scores.size(); i++)
System.out.println(scores.get(i)); //Prints out the arraylist of scores entered
System.out.println("_____");
System.out.println(scores.size()); //prints out the size of the arraylist but is wrong
}

for 循环之后的以下代码只是为了确保它正常运行,但不幸的是事实并非如此。看起来好像只是将一些数字读入 ArrayList 所以我得到的输入是:

   Enter the scores of the student, press Q to finish
12
13
14
145
14
13
q
___________
13
145
13
_____
3

因此,当我在奇数位置输入 q(退出循环)时,程序将退出循环,但读入 ArrayList 的唯一数字是偶数位置的数字。当我在偶数位置输入 q 时,出现以下错误:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Chapter_7.GradeBook.enterScores(GradeBook.java:36)
at Chapter_7.GradeBookTester.main(GradeBookTester.java:12)

最佳答案

试试这个:

public void enterScores() {
Scanner userInput = new Scanner(System.in);
System.out.println("Enter the scores of the student, press Q to finish");
for (int i = 0; i < SCORES_SIZE; i++) {
String input = userInput.next();
if ("Q".equals(input)) {
break;
}
try {
scores.add(i, Integer.parseInt(input));
} catch (NumberFormatException e) {
System.out.println("entered value can not be casted to integer");
}
}
}

关于java - java 如何退出for循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47729862/

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