您好我正在编写将接受用户输入并将用户输入放入ArrayList的java代码,但我希望用户能够在输入所有数据时输入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)
答案 0 :(得分:1)
试试这个:
manifest