Java入門 #14 - 標準入力(Scanner クラス)

入門 | 10分 で読める | 2026.05.02

公式ドキュメント

この記事の要点

Scanner クラスでキーボード入力を受け取れる
• `nextInt()` / `next()` / `nextLine()` の違いを理解する
• 使用後は 必ず close() するか、try-with-resources を使う

Scanner クラスとは

コンソールアプリでユーザーと対話するには、標準入力(キーボード入力) を読み取る必要があります。Java では java.util.Scanner クラスを使います。

機能説明
標準入力の読み取りSystem.in から1行ずつ、または1単語ずつ取得
型変換入力を int / double / String 等に自動変換
ファイル入力にも対応標準入力だけでなくファイルからも読める

基本的な使い方

1. import

Scanner クラスは java.util パッケージにあるため、import が必要です。

import java.util.Scanner;

ポイント: `String` や `System` は `java.lang` パッケージなので import 不要ですが、`Scanner` は `java.util` なので明示的に import します。

2. Scanner オブジェクトを作る

Scanner scanner = new Scanner(System.in);

System.in標準入力ストリームを表します。これを Scanner のコンストラクタに渡すことで、キーボード入力を読み取れるようになります。

3. 入力を読み取る

String name = scanner.next();  // 次の単語を読む
int age = scanner.nextInt();   // 次の整数を読む

4. 使い終わったら閉じる

scanner.close();

注意: `Scanner` を閉じずに終了すると、リソースリークの警告が出ることがあります。必ず `close()` を呼ぶか、次のセクションで紹介する try-with-resources を使いましょう。

主要メソッド一覧

メソッド読み取る内容備考
next()次の単語(空白区切り)スペースや改行で区切られた単語
nextLine()次の1行全体Enter まで読む(空白を含む)
nextInt()次の整数改行は消費しない(注意点あり)
nextDouble()次の浮動小数点数同上
nextBoolean()次の真偽値true / false
hasNext()次の入力が存在するかboolean を返す
hasNextInt()次の入力が整数か同上

nextInt() と nextLine() の違い(重要)

初心者がよく躓くポイントです。

// Java 21
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("年齢を入力: ");
        int age = scanner.nextInt();  // ここで「25」と入力してEnter

        System.out.print("名前を入力: ");
        String name = scanner.nextLine();  // ここが空文字になる!

        scanner.close();

        System.out.println("名前: " + name + ", 年齢: " + age);
    }
}

問題点: nextInt()改行文字を消費しないため、次の nextLine() が改行だけを読んで終わってしまいます。

解決策1: nextLine() で読んで変換する

int age = Integer.parseInt(scanner.nextLine());

解決策2: nextInt() の後に nextLine() を1回呼んで改行を捨てる

int age = scanner.nextInt();
scanner.nextLine();  // 改行を捨てる
String name = scanner.nextLine();

補足: 個人的には**解決策1(すべて nextLine() で読んで必要なら変換)** が安全でおすすめです。

try-with-resources で自動クローズ

Java 7 以降、try-with-resources を使うと close() を自動的に呼んでくれます。

// Java 21
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("名前を入力: ");
            String name = scanner.nextLine();

            System.out.print("年齢を入力: ");
            int age = Integer.parseInt(scanner.nextLine());

            System.out.printf("こんにちは、%s さん(%d歳)%n", name, age);
        }
        // ここで自動的に scanner.close() が呼ばれる
    }
}

ポイント: `try (...)` のカッコ内で作った Scanner は、try ブロックを抜ける際に自動的にクローズされます。明示的に `close()` を書く必要がありません。

実践例: 名前と年齢を聞いて挨拶する

// Java 21
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            // 名前を聞く
            System.out.print("あなたの名前を入力してください: ");
            String name = scanner.nextLine();

            // 年齢を聞く
            System.out.print("あなたの年齢を入力してください: ");
            int age = Integer.parseInt(scanner.nextLine());

            // 挨拶
            if (age < 20) {
                System.out.printf("こんにちは、%s さん!未成年ですね。%n", name);
            } else {
                System.out.printf("こんにちは、%s さん!成人ですね。%n", name);
            }
        } catch (NumberFormatException e) {
            System.out.println("年齢は整数で入力してください。");
        }
    }
}

実行例:

あなたの名前を入力してください: Alice
あなたの年齢を入力してください: 25
こんにちは、Alice さん!成人ですね。

注意: ユーザーが数値以外を入力すると `NumberFormatException` が発生します。本格的なプログラムでは `try-catch` でエラーハンドリングをしましょう。

入力のバリデーション

ユーザーが想定外の値を入れることは日常茶飯事です。hasNextInt() などで事前チェックできます。

// Java 21
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("整数を入力: ");

            if (scanner.hasNextInt()) {
                int num = scanner.nextInt();
                System.out.println("入力された数値: " + num);
            } else {
                System.out.println("整数を入力してください。");
            }
        }
    }
}

Scanner のその他の用途

標準入力だけでなく、ファイルや文字列からも読み取れます(応用)。

用途コンストラクタ
標準入力new Scanner(System.in)
ファイルnew Scanner(new File("data.txt"))
文字列new Scanner("123 456 789")

例(文字列から読む):

Scanner scanner = new Scanner("10 20 30");
int a = scanner.nextInt();  // 10
int b = scanner.nextInt();  // 20
int c = scanner.nextInt();  // 30
scanner.close();

補足: 文字列を数値に分割するときに便利です。ファイル入出力は別の記事で扱います。

よくある間違いと対処法

間違い原因対処法
nextLine() が空になるnextInt() が改行を残すnextLine() で統一するか、改行を捨てる
数値以外を入力してクラッシュNumberFormatExceptiontry-catch で捕捉するか hasNextInt() でチェック
Scanner を閉じ忘れリソース管理の意識不足try-with-resources を使う
複数の Scanner を同時に使うSystem.in を閉じると再度開けない1つの Scanner を使い回す

まとめ

概念説明
Scanner標準入力・ファイル・文字列から読み取るクラス
import 必須java.util.Scanner を import する
next() / nextLine() の違いnext() は単語、nextLine() は1行全体
nextInt() の罠改行を残すので nextLine() と併用時は注意
close() 必須使用後は close() するか try-with-resources を使う
hasNextXxx()入力の型チェックに使える

次のステップ

Java入門 #15 - ArrayList の基本 で可変長の配列(リスト)を学びます。

参考リソース

この技術を体系的に学びたいですか?

未来学では東証プライム上場企業のITエンジニアが24時間サポート。月額24,800円から、退会金0円のオンラインIT塾です。

メールで無料相談する
← 一覧に戻る