LoginSignup
8
6

More than 3 years have passed since last update.

nextInt()→nextLine()の落とし穴

Posted at

数字と文字列の2つのパラメータを標準入力で渡したいと思います。

使うメソッドは、
nextLine():改行までの一行分の入力を取得することができるメソッド
nextInt() :int型の数値を取得することができるメソッド
この2種類ですが、
順番が問題です。

nextLine()が先だと、入力を2回受け付けてくれます。


import java.util.*;

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

        Scanner sc = new Scanner(System.in);

        String numStr = sc.nextLine();
        int num = sc.nextInt();

        sc.close();

        System.out.println(num);
        System.out.println(numStr);
    }
}

nextLine()が後だと、入力を1回しか受け付けてもらえません。
numStrには空文字が入ります。


import java.util.*;

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

        Scanner sc = new Scanner(System.in);

        int num = sc.nextInt();
        String numStr = sc.nextLine();

        sc.close();

        System.out.println(num);
        System.out.println(numStr);
    }
}

これは、nextIntで数値を読み込んだ際、改行文字が残ってしまっているためです。
int+enter(\n)
その残った改行文字をnextLineで読み込んでしまっています。

順番を変える以外の解決策としては、

int num = sc.nextInt();
sc.nextLine();←改行をここで読み込ませる。(変数には格納する必要なし)
String numStr = sc.nextLine();

があります。

8
6
1

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
8
6