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

More than 3 years have passed since last update.

キーボードから入力する(InputStreamReader/Scanner)【Java】

0
Posted at

Javaにはキーボードから文字を入力するための「InputStreamReader」や「Scanner」がある。標準入力を扱うことができるので上手く活用してみよう。

「標準入力」とは

標準入力とはキーボードから文字を入力すること。標準入力を使えばキーボードから入力した文字を表示させたり、文字によってプログラムの動作を分岐させることなどができる。

「InputStreamReader」でキーボードから入力する方法

キーボードから入力するには「InputStreamReaderクラス」、「BufferedReaderクラス」、「readLineメソッド」を組み合わせて使う。

次のプログラムで確認してみましょう。

Main.java
import java.io.IOException;
import java.io.InputStreamReader;
 
public class Main {
 
    public static void main(String[] args) {
 
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
 
        System.out.println("キーボードから入力してください");
 
        String str = null;
        try {
            str = br.readLine();
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        System.out.println("入力された文字は「" + str + "」です");
 
    }
 
}
//実行結果
キーボードから入力してください
Samurai
入力された文字は「Samurai」です

※このプログラムでは、「Samurai」と入力している。

Scannerでキーボードから入力する方法

Scannerで入力を受け付け、nextメソッドで入力された文字を読み取る。
次のプログラムで確認してみましょう。

Main.java
import java.util.Scanner;
 
public class Main {
 
    public static void main(String[] args) {
 
        System.out.println("キーボードから入力してください");
 
        Scanner scan = new Scanner(System.in);
 
        String str = scan.next();
 
        System.out.println("入力された文字は「" + str + "」です");
 
    }
 
}
//実行結果
キーボードから入力してください
Samurai
入力された文字は「Samurai」です

※このプログラムでは、「Samurai」と入力している。

nextIntメソッドで数値を入力する方法

nextメソッドは入力された文字を文字列として読み込みますが、nextIntメソッドは数値として読み込む。
次のプログラムで確認してみましょう。

Main.java
import java.util.Scanner;
 
public class Main {
 
    public static void main(String[] args) {
 
        System.out.println("キーボードから入力してください");
 
        Scanner scan = new Scanner(System.in);
 
        int num = scan.nextInt();
 
        System.out.println("入力された文字は「" + num + "」です");
 
    }
 
}
//実行結果
キーボードから入力してください
123
入力された文字は「123」です

※このプログラムでは、「123」と入力しています。

参考サイト

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