中級 › 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
空欄を埋めてビルドを通す
hasNextIntで判定しnextIntで読んでいるのに余分なnextLineを挟むと、最後の行で読む相手がなくなり例外になります。
次の問題