LoginSignup
0
0

More than 3 years have passed since last update.

Java基礎

Posted at

自分の復習用に

「0から2入力」があれば「0から2で入力してください」と表示
「文字列の入力」があれば「整数値ではありません」と表示

try-catchを使用するのではなくScannerのhasNextが使えたので
こういうやり方があると記録しておく。

hello.java

      void getJudgeHand() {
        while (true) {
            System.out.println("コマンド? 0:グー 1:パー 2:チョキ");
            if (scanner.hasNextInt()) {
                myHand = scanner.nextInt();
                if (myHand >= 0 && myHand <= 2) break;
            }
            else {
                scanner.next();
                System.out.println("整数値ではありません");
            }
            System.out.println("0から2で入力してください");
        }
    }

try-catchの方法も

hello.java


void getJudgeHand() {
    while (true) {
        try {
            System.out.println("コマンド? 0:グー 1:パー 2:チョキ");

            this.myHand = scanner.nextInt();
            if (this.myHand <= 2 && this.myHand >= 0) { // 2以下 かつ、0以上ならbreak
                break;
            }
        } catch (InputMismatchException e) {
            System.out.println("整数値ではありません");
            scanner.next();    // 入力を捨てる
        }
        System.out.println("0から2で入力してください");
    }
}



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