Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@htnnn17

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



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
0
Help us understand the problem. What are the problem?