11
2

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#2 〜基本編②-nextLine-〜

Posted at

はじめに

前回の記事 #1 で「Scannerは読み取り係」だと分かりました。
今回は いちばんよく使う基本技nextLine() で「質問→1行読む→すぐ返事」を作ります。シンプルだけど、実務でもこれが土台です。


🎓 今日やること(ゴール)

  • キーボードから 1行だけ 読む。
  • 受け取った文字列を そのまま表示 できる。
  • 空白だけの入力 をやさしく弾ける。

🔧 3ステップ

  1. Scanner を1つ用意する(標準入力:new Scanner(System.in))。
  2. 文字列を nextLine() で受け取る(Enterまで丸ごと)。
  3. trim() してから判定(空なら聞き直し)。

標準入力の Scannercloseしない
System.in が閉じると再入力できなくなるため)。


✅ 最小コード(コピペOK)

import java.util.Scanner;

public class Main {
    private static final Scanner SC = new Scanner(System.in);

    public static void main(String[] args) {
        String nick = ask("ニックネーム");
        System.out.println("登録: nick=" + nick);
    }

    // 空白だけの入力はやり直す、やさしい質問メソッド
    static String ask(String label) {
        while (true) {
            System.out.print(label + "> ");
            String s = SC.nextLine().trim();
            
            if (!s.isEmpty()){
                return s;
            }
            System.out.println("入力が空です。もう一度お願いします。");
        }
    }
}

🧭 よくあるつまずき(先に回避)

  • 改行だけ受け取ってしまうtrim() して空なら聞き直す。
  • close() してしまう:標準入力は閉じない。
  • nextInt() を混ぜる:今日は使いません(改行問題は後日扱います)。

⚡ ピカチュウ例:2質問→1行要約

ニックネームとタイプを聞いて、1行でまとめます。

import java.util.Scanner;

public class Main {
    private static final Scanner SC = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("あなたのピカチュウの情報を入力せよ");
        
        String nick = ask("ニックネーム");
        String type = ask("タイプ(例: でんき)");
        
        System.out.println("記録: nick=" + nick + " type=" + type);
    }

    static String ask(String label) {
        while (true) {
            System.out.print(label + "> ");
            String s = SC.nextLine().trim();
            
            if (!s.isEmpty()){
                return s;
            }
            System.out.println("入力が空です。もう一度お願いします。");
        }
    }
}

あとがき

これで 一問一答の土台 が作れました。
次回は、文字で受け取った入力を 安全に数値へ変換 するやり方
(エラー時は聞き直す)に進みます。

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

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

11
2
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
11
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?