1
こんにちは私は、ユーザー入力を受け取り、ArrayListにユーザー入力を配置するJavaコードを書いていますが、ユーザーがすべてのデータを入力したときにQを入力できるようにします。しかし、特定のインスタンスでqを入力すると、間違った出力が得られます。forループjavaを終了するには?
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ループの後の次のコードは、私がそれが正しく動作していたことを確認することができただけでしたが、残念ながらそれはありません。
Enter the scores of the student, press Q to finish
12
13
14
145
14
13
q
___________
13
145
13
_____
3
私は奇妙な位置に(ループを終了する)のqを入力するときに、プログラムが終了します:私は取得しています入力があるので、それが唯一のArrayListに数字のいくつかを読んでいるかのように思えますループではなく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)
[スキャナからの文字入力してください](HTTPSの可能性のある重複:// stackoverflowの.com/questions/13942701/take-a-char-from-the-scanner) – Steephen
は 'next()'を使って 'String'入力を受け取ります。最初の文字を抽出します。 'nextInt()'は例外を与えます。なぜなら、 'Q'が入力であるとき、解析された入力は整数ではないからです。 –