LoginSignup
0
0

More than 3 years have passed since last update.

Javaの標準入力のScannerで詰まった話

Last updated at Posted at 2019-07-27

Javaの標準入力で詰まってしまった

題名の通りJavaの標準入力を取得する際に詰まったので
Scannerの違い

今回登場するScannerのメソッドは
- next();
- nextInt();
- nextLine();
の3つ。

next();

これは標準入力を空白まで読み取ってくれる。

標準入力: a 123 →取得: a

nextInt();

これも標準入力を空白まで読み取ってくれる。
返り値はint

標準入力: 1 abc →取得: 1

nextLine();

これが上2つとは違って2つの注意点。
- 改行(\n)まで読み込む
- 空白も読み取る
返り値はString

例1

標準入力

1
aa

取得

1

これは一行で書くなら 1\naa なので \n の前の 1 まで読んで読み取り開始位置は aa の前

例2

標準入力

1 abc
aa

取得

1 abc

これは一行で書くなら 1 abc\naa なので \n の前の 1 abc まで読んで読み取り開始位置は aa の前

上記を踏まえると

標準入力

a
2 3
b
4
c

として全ての数字/文字を取りたければ

1. next(); or nextLine(); →a
2. nextInt(); →2
3. nextInt(); →3
4. next(); →b
5. nextInt(); →4
6. next(); or nextLine();→c

となる。

0
0
2

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
0