数当てゲーム

Number Guessing Game

ランダムで生成される正解値を10回以内の予想で当てるゲームです。
整数外の入力や範囲外の数の入力は弾いて予想回数に入れないようにしています。


import java.util.*;

// geschrieben von Beliar698ma

class NumGuess {
  public static void main(String[] args) {

    int guessCount = 1;
    int userGuess = 0;
    String guessHistory = "予想履歴: ";
    int randomNum = (int)Math.floor(Math.random() * 100) + 1;

    Scanner sc = new Scanner(System.in);

    while(true) {

      if (guessCount == 11) {
        System.out.println("!!! GAME OVER !!!");
        break;
      }

      System.out.println("予想値を入力してください。");

      if (sc.hasNextInt()) {
        userGuess = sc.nextInt();
      } else {
        System.out.println("有効な値を入力してください。");
        sc.next();
        continue;
      }

      if (userGuess < 1 || 100 < userGuess) {
        System.out.println("1 ~ 100の値を入力してください。");
        continue;
      }

      if(userGuess == randomNum) {
        guessHistory += userGuess + ", ";
        System.out.println(guessHistory.substring(0, guessHistory.length() - 2));
        System.out.println("おめでとうございます!正解です!");
        break;
      } else if (userGuess < randomNum) {
        guessHistory += userGuess + ", ";
        System.out.println(guessHistory.substring(0, guessHistory.length() - 2));
        System.out.println("予想値は正解値より小さいです。");
      } else if (userGuess > randomNum) {
        guessHistory += userGuess + ", ";
        System.out.println(guessHistory.substring(0, guessHistory.length() - 2));
        System.out.println("予想値は正解値より大きいです。");
      }
      
      guessCount++;
    }
    sc.close();
  }
}