13
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#3 〜数字入力:安全に文字→数値へ〜

Posted at

はじめに

前回の記事 #2 では nextLine() で「一行を読み取る方法」を学習しました。
ここから一歩進んで、文字で受け取った入力を安全に数値へ変換 する方法を学びます。


今日のゴール

  • 文字列で受けてから Integer.parseIntDouble.parseDouble で数値に変える。
  • まちがって入力されたら やさしく聞き直すループ を書ける。

3ステップ

  1. 入力はまず nextLine() で文字として受ける
  2. trim() して余計な空白を落とす。
  3. try { パース } catch { メッセージを出して聞き直し }

最小コード(コピペOK)

import java.util.Scanner;

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

    public static void main(String[] args) {
        int level = askInt("レベル(整数)");
        double weight = askDouble("体重kg(小数可)");
        System.out.printf("記録: level=%d weight=%.1fkg%n", level, weight);
    }

    static int askInt(String label) {
        while (true) {
            System.out.print(label + "> ");
            String s = SC.nextLine().trim();
            try {
                return Integer.parseInt(s);
            } catch (NumberFormatException e) {
                System.out.println("整数で入力してください(例: 42)。");
            }
        }
    }

    static double askDouble(String label) {
        while (true) {
            System.out.print(label + "> ");
            String s = SC.nextLine().trim();
            try {
                return Double.parseDouble(s);
            } catch (NumberFormatException e) {
                System.out.println("小数で入力してください(例: 6.5)。");
            }
        }
    }
}

よくあるつまずきポイント!

  • カンマや単位を混ぜない1,2346.5kg はそのままでは変換できません。
  • 全角数字で入力しない123 はエラーになります。
  • 小数点の表記に注意:小数点は .(ドット)を使います(3.14)。
  • 範囲チェック:値が正しいとは限りません(例:レベルは 1 ~ 100など)

ピカチュウ例:レベルと体重を安全に記録

import java.util.Scanner;

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

    public static void main(String[] args) {
        int level = askInt("レベル(1以上の整数)");
        while (level < 1) {
            System.out.println("1以上でお願いします。");
            level = askInt("レベル(1以上の整数)");
        }
        double weight = askDouble("体重kg(小数可)");
        System.out.printf("記録: ピカチュウ level=%d weight=%.1fkg%n", level, weight);
    }

    static int askInt(String label) {
        while (true) {
            System.out.print(label + "> ");
            String s = SC.nextLine().trim();
            try { 
                return Integer.parseInt(s);
            }catch (NumberFormatException e) { 
                System.out.println("整数で入力してください。"); 
            }
        }
    }

    static double askDouble(String label) {
        while (true) {
            System.out.print(label + "> ");
            String s = SC.nextLine().trim();
            try { 
                return Double.parseDouble(s);
            } catch (NumberFormatException e) { 
                System.out.println("小数で入力してください。");
            }
        }
    }
}

あとがき

これで 数字を安全に受け取る基本 ができました。
次回 #4 は、多くの人がハマる 「改行問題」nextInt() のあとに nextLine()
空になる)を、原因からやさしく解決します。

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

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

13
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
13
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?