LoginSignup
1
0

More than 1 year has passed since last update.

Scanner.nextInt()の落とし穴

Posted at

Scanner.nextInt()の落とし穴

これはあまり参考書などに載っていなくて、ちょっと苦労したコードの落とし穴を記事として記しておきます。
もし、同じような落とし穴にはまってしまった人の参考になれば幸いです。

エラーの内容

以下のようなコードを実行すると、

あなたの年齢は?
44
あなたの名前は?
あなたの名前:   あなたの年齢は: 44

年齢を入力したあと、間髪入れずに

あなたの名前は?
あなたの名前: あなたの年齢は: 44

と表示されてしまいます。

エラーの理由

これは、整数を入力したあとのエンターキーの入力がStringとして残っていて悪さをしてしまいます。そのため、
整数を入力したあとのエンターキーの入力を処理する必要があります。

該当するソースコード

import java.util.Scanner;



public class Main {
   public static void main(String[] args) throws Exception {

       Scanner scanner= new Scanner(System.in);
       System.out.println("あなたの年齢は?");

       int age = scanner.nextInt();
       System.out.println("あなたの名前は?");
       String name = scanner.nextLine();


       System.out.println("あなたの名前: " + name + "  " + "あなたの年齢は: " + age );




   }
}

直したソースコード

import java.util.Scanner;



public class Main {
   public static void main(String[] args) throws Exception {

       Scanner scanner= new Scanner(System.in);
       System.out.println("あなたの年齢は?");
       int age = scanner.nextInt();
       scanner.nextLine();  //注目!!13行目
       System.out.println("あなたの名前は?");
       String name = scanner.nextLine();

       System.out.println("あなたの名前: " + name + "  " + "あなたの年齢は: " + age );
   }
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0