Help us understand the problem. What is going on with this article?

Java基礎

自分の復習用に

「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で入力してください");
    }
}



htnnn17
覚えておきたいことをかきためる
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした