import java.util.Scanner;
を使用する。
hasNextInt()
を使用することでユーザーからインプットされる値がintかどうかtrue/falseで確認できる
値の取り出しはnextInt()
を使用する
scanner.close()
を忘れずに!
追記 4/10/2020
Stringの場合はnextLine()
が必要。
と上記で書いていますが、nextInt()
のときもEnter(改行コード)を押すことになるので、
int a = scanner.nextInt();
scanner.nextLine();
とすることを推奨します。
また、ユーザーInputを促すと、何故か2回入力させられる現象に出会いました。
自分的にはnextInt()
以外でユーザーInputをさせていないのだと勘違いしていました。
例えば下記のようなコード
if(!scanner.hasNextInt()) { //error logic } else if (scanner.nextInt() == 0) { //error logic }
上記はhasNextInt()
にて入力されていることになることを理解。
文字を1回入力+Enterを入力..を二回しないといけなくなります。
サンプルコード
import java.util.Scanner; public class Main { public static void main(String[] args) { int loopCnt = 1; int userInput = 0; Scanner scanner = new Scanner(System.in); while (loopCnt <= 10) { System.out.println("Enter number #" + loopCnt); boolean isNextInt = scanner.hasNextInt(); if (isNextInt) { userInput += scanner.nextInt(); } else { System.out.println("Invalid Input"); break; } loopCnt++; } System.out.println("Sum of your entered number :" + userInput); scanner.close(); } }