Javaの標準入力
諸事情によりJavaで競プロをすることになったので、標準入力の方法をまとめます。
初心者なのでとりあえずScannerでの受け取り。
1行に1つの文字または数字
最も基本となる標準入力方法。
Scanner sc = new Scanner(System.in); int n = sc.nextInt();
型にあわせて
- nextLong()
- next()
を使う。
1行に複数の数字(配列へ)
11 234 55
など。
Scanner sc = new Scanner(System.in); int[] a = new int[n]; Arrays.setAll(a, i -> sc.nextInt());
nextInt()
をfor文でまわすだけの方法もある。
Scanner sc = new Scanner(System.in); int[] numbers = new int[n]; for(int i=0; i<n; i++){ numbers[i]=sc.nextInt(); }
1行に複数の文字列(配列へ)
foo bar hoge
など。
Scanner sc = new Scanner(System.in); String[] words = sc.nextLine().split(" ");
1つの文字列を1文字ずつ配列へ
oo..xoxxx.o
などを受け取る。
Scanner sc = new Scanner(System.in); char[] s = sc.next().toCharArray();
複数行の文字列(地図など)
###..##
などで表現される地図を受け取る。
Scanner sc = new Scanner(System.in); char[][] map = new char[r][c]; for (int row = 0; row < r; row++) { map[row] = sc.next().toCharArray(); }