10
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【ポケモン×Java】知識編 Scanner#4 〜改行問題の正体と対策〜

Posted at

はじめに

Scannerを使っていると、よくあるつまずきがこの 改行問題 です。

nextInt() のあとに nextLine() を呼んだら、空っぽが返ってきた…なぜ?

今日は「なにが起きてるのか」をやさしく見て、2つの回避策を身につけます。


今日のゴール

  • nextInt()nextLine()読み方の違いを理解する。
  • 回避A:最初から nextLine() で受けてから数値に変換(おすすめ)。
  • 回避B:nextInt() の直後に 改行を1つ捨てる(状況によっては便利)。

そもそも、なにが起きてるの?

  • nextInt() は「数字のまとまりだけ」を読みます。**Enter(改行)**は読み残します。
  • 続けて nextLine() を呼ぶと、さっき残った改行だけを読んでしまい、空文字になります。

図にすると:

入力:  23\nピカチュウ\n
        ↑
nextInt() は 23 だけ読む/\n は残る
その直後の nextLine() は 残った \n を読む → 空文字

つまずきを体験(よくある失敗)

import java.util.Scanner;

public class BadSample {
    private static final Scanner SC = new Scanner(System.in);
    public static void main(String[] args) {
        System.out.print("年齢(int)> ");
        int age = SC.nextInt(); // 改行は残る

        System.out.print("好きな技> ");
        String move = SC.nextLine(); // ← 空文字になりがち

        System.out.println("age=" + age + " move=" + move);
    }
}

回避A(おすすめ):全部 nextLine() → 変換

考え方をシンプルにする方法です。数字もまずは文字で受け取り、あとで変換します。

import java.util.Scanner;

public class FixA {
    private static final Scanner SC = new Scanner(System.in);
    public static void main(String[] args) {
        int age = askInt("年齢(int)");
        String move = askLine("好きな技");
        System.out.println("age=" + age + " move=" + move);
    }
    
    static String askLine(String label) {
        while (true) {
            System.out.print(label + "> ");
            String s = SC.nextLine().trim();
            
            if (!s.isEmpty()){
                return s;
            }
            
            System.out.println("入力が空です。もう一度お願いします。");
        }
    }
    
    static int askInt(String label) {
        while (true) {
            String s = askLine(label);
            try { 
                return Integer.parseInt(s);
            } catch (NumberFormatException e) { 
                System.out.println("整数で入力してください。");
            }
        }
    }
}

ポイント

  • 改行問題そのものが発生しません。
  • 入力チェック(空白・形式間違い)を1か所で統一できます。

回避B:nextInt() の直後に改行を1つ捨てる

既存コードを大きく直せないときなどに使う小手先の対策です。

import java.util.Scanner;

public class FixB {
    private static final Scanner SC = new Scanner(System.in);
    public static void main(String[] args) {
        System.out.print("年齢(int)> ");
        int age = SC.nextInt();
        SC.nextLine(); // ← 残った改行をここで消費

        System.out.print("好きな技> ");
        String move = SC.nextLine();
        System.out.println("age=" + age + " move=" + move);
    }
}

ポイント

  • 1個の改行だけを想定。入力のパターンが複雑だと、ずれることがあります。
  • 新規開発では回避Aのほうが安定です。

よくある取り違え

  • nextInt()nextLine() の違い
    nextInt() は空白で区切られた1語(数字)、nextLine() は行全体。
  • 複数の数値を1行で入れる
    nextInt() を複数回呼ぶと、意図通り動くが、
    次に nextInt() を使うなら改行消費を忘れずに

ピカチュウ例:レベルと好きな技を正しく取得(回避A版)

import java.util.Scanner;

public class PokeMemo {
    private static final Scanner SC = new Scanner(System.in);
    public static void main(String[] args) {
        int level = askInt("レベル(int)");
        String move = askLine("好きな技");
        System.out.println("記録: level=" + level + " move=" + move);
    }
    
    static String askLine(String label) {
        while (true) {
            System.out.print(label + "> ");
            String s = SC.nextLine().trim();
            
            if (!s.isEmpty()){
                return s;
            }
            
            System.out.println("入力が空です。もう一度お願いします。");
        }
    }
    
    static int askInt(String label) {
        while (true) {
            String s = askLine(label);
            
            try { 
                return Integer.parseInt(s);
            } catch (NumberFormatException e) { 
                System.out.println("整数で入力してください。");
            }
        }
    }
}

あとがき

これで、Scannerの最大のつまずきポイントを確認しました。
次回 #5 は、複数行の入力を最後まで読む方法と、1行の中を
カンマ区切りで分ける 基本を学びます。

💬 コメント・フィードバック歓迎!

「この章わかりやすかった!」
「これ表現まちがってない?」
「次は○○をやってほしい!」などなど、
お気軽にコメントで教えてくださいね!

10
1
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
10
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?