Code Fix

中級 › nextInt の後の nextLine が読み飛ばされる理由 › パターン5

nextInt の後の nextLine が読み飛ばされる理由

改行文字の読み残しが原因です。

 1  import java.util.Scanner;
 2  
 3  public class Main {
 4      public static void main(String[] args) {
 5          Scanner sc = new Scanner("1\n2\n3");
 6          int sum = 0;
 7          while (sc.hasNextInt()) {
 8              sum += sc.nextInt();
 9              ______________
                       ^
10          }
11          System.out.println(sum);
12      }
13  }
Exception in thread "main" java.util.NoSuchElementException: No line foundexited with code 1

空欄を埋めてビルドを通す

広告
広告スロット(未設定)

nextInt の後の nextLine が読み飛ばされる理由

判定と読み取りの単位を揃える設計を扱います。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)