Skip to content

Instantly share code, notes, and snippets.

@mokomokohitsuzi
Last active January 7, 2020 00:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mokomokohitsuzi/9b367714c1b7098d137d7d23d11ed92f to your computer and use it in GitHub Desktop.
Save mokomokohitsuzi/9b367714c1b7098d137d7d23d11ed92f to your computer and use it in GitHub Desktop.
新・明解Java入門 演習4-27
import java.util.Random;
import java.util.Scanner;
public class En4_27 {
public static void main(String[] args) {
Random rand = new Random();
Scanner stdIn = new Scanner(System.in);
// 最大回数を設定。
final int MAX = 7;
int no = rand.nextInt(100);
System.out.println("数当てゲーム開始!!");
System.out.println("0~99の数を" + MAX + "回で当てて下さい。");
int x;
// 回数を判定するための変数
int count = 0;
// ラベルを設定
Game:
// 無限ループを作成(ループすれば何でも良いと思われる)
while (true) {
if (count == MAX) {
// count変数が設定した数と同じ値になった場合、成果を表示してゲームを終了。
System.out.println("正解は" + no + "でした。\nゲームを終了します。");
// breakでGameラベルを抜ける。
break Game;
}
System.out.print("いくつかな?:");
x = stdIn.nextInt();
count++;// カウント値の増加
if (x > no) {
// カウントがMAXでなければヒントを出す
if (count != MAX) {
System.out.println("もっと小さな数だよ。");
}
} else if (x < no) {
// カウントがMAXでなければヒントを出す
if (count != MAX) {
System.out.println("もっと大きな数だよ。");
}
} else {
// 正解の場合の表示
System.out.println("正解です。");
// breakでGameラベルを抜ける。
break Game;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment