LoginSignup
3
1

More than 3 years have passed since last update.

【Java】標準入力を取得・出力する方法

Last updated at Posted at 2020-12-21

プログラミング勉強日記

2020年12月21日
Cでは標準入力を使ったことがあるが、Javaで標準入力を使ったことがなかった。その今日勉強した内容をまとめる。

標準入力・標準出力とは

 簡単に言うとキーボードからの入力のことを標準入力という。JavaではSysytemクラスのinフィールドで標準入力を取得する。

 標準出力は、プログラムからデータを表示するための装置のようなもので、ディスプレイに表示されるものをいう。JavaではSysteクラスのoutフィールドを使う。

Scannerの使い方

 java.util.Scannerクラスには以下のようなメソッドが用意されている。

  • 1行分の入力を取得するnextLineメソッド
  • 空白文字までの入力を取得するnextメソッド
  • 数値の入力を取得するnextIntメソッド

nextLineメソッドの使い方

 nextLineメソッドは、改行までの1行分の入力を取得することができる。

サンプルコード
import java.util.Scanner;

public class Sample {
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String str = scan.nextLine();

    System.out.println(str);
    scan.close();
  }
}

nextメソッドの使い方

 nextメソッドは、空白文字までの入力を取得できる。

サンプルコード
import java.util.Scanner;

public class Sample {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String str1 = scan.next();
        String str2 = scan.next();

        System.out.println(str1);
        System.out.println(str2);
        scan.close();
    }
}

nextIntの使い方

 nextIntを使うとint型の数値を取得できる。浮動小数点型のすうちを取得するnextDoubleメソッドやnextFloatメソッドもある。

サンプルコード
import java.util.Scanner;

public class Sample {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num1 = scan.nextInt();
        int num2 = scan.nextInt();

        int sum = num1 + num2;
        // 入力した数値の足し算を出力する
        System.out.println(num1 + " + " + num2 + " = " + sum);
        scan.close();
    }
}

参考文献

クラスScanner
【Java入門】標準入力を取得、出力する方法(Scannerを解説)

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