1
0

Scannerを用いた標準入力まとめ

Posted at

個人的な備忘録も含めてScannerを用いた様々な標準入力をまとめてみた。

Scaneerクラスの基本的な使い方

1.「java.util.scanner」をimportする
2. Scannerクラスのインスタンスを作成(引数にはSystem.inを指定)

主な入力メソッド

メソッド 内容
next() 空白までの文字列を取得
nextLine() 1行分の文字列を取得
nextInt() 入力した文字を整数型に変換。※整数以外を入力するとエラー

1. 基本的な使用

import java.util.Scanner;

public class Main{
    public static void main(String[] args){
    //Scannerクラスのインスタンス作成
    Scanner scanner = new Scanner(System.in);

    //入力内容を取得
    String text = scanner.next();

    //入力内容出力
    System.out.println(text);
    }
}
/*入力内容がそのまま出力される。
入力値:リンゴ
出力値:リンゴ
*/

異なる行で複数の入力値を受け取る

・入力値の数が3つの場合

import java.util.*;

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

        //入力値を格納する配列を作成
        String[] str= new String[3];

        //入力値を配列に代入
        for(int i=0; i<3; i++){
            str[i] = scanner.next();
         }
        //入力内容を出力
         for(int i=0; i<3; i++){
            System.out.println(str[i]);         
        
 }
}

/*入力値
りんご
ばなな
めろん

出力値
りんご
ばなな
めろん
*/

・入力する要素数を最初に指定する

import java.util.*;

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

        //格納する要素数を指定
        int num = scanner.nextInt();
        //入力
        String[] str= new String[num];
        for(int i=0; i<num; i++){
            str[i] = scanner.next();
         }
         //出力
        for(int i=0; i<num; i++){
            System.out.println(str[i]);         
        }
    }
}
/*入力
3
入力1
入力2
入力3

出力値
入力1
入力2
*/

半角スペース区切られた入力値を受け取る

import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // Your code here!
        Scanner scanner = new Scanner(System.in);
        String[][] str = new String[3][2];
        
        for(int i=0; i<3; i++){
            for(int j=0; j<2; j++){
                str[i][j] = scanner.next();
            }
        }
        for(int i=0; i<3; i++){
            for(int j=0; j<2; j++){
                System.out.print(str[i][j]);
            }
            System.out.println("");
        }
        }
    }
/*入力
1 2
3 4
5 6

出力
12
34
56
*/

参考

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