私は比較的新しいjavaです。これは初めてif else文を扱うときです。私はユーザーが1-3の間の数字を推測する基本的なゲームを作ろうとしていて、プログラムはそれらが正しいか間違っているかを伝えます。しかし、プログラムを実行すると、1をタイプするとプログラムが応答せず、Ctrl-Eを使用して終了する必要があります。私は間違って何をしていますか?私が1以外の値を入力すると、「さようなら」を印刷してプログラムを実行します。これが私の最初の時間をここに掲載されてjava if文が実行されていない
import java.util.*;
public class GuessTheNumber {
public static void main(String[] args) {
Scanner game = new Scanner(System.in);
Random rand = new Random();
System.out.println("Hey there! Want to play a game?");
System.out.println("\tIf yes, type 1");
System.out.println("\tIf no, type 2");
int ans1 = game.nextInt();
if (ans1 == 1) { // This is true, yet when I type 1, nothing happens.
int randomNum = rand.nextInt((3 - 1) + 1) + 1;
int guess = game.nextInt();
System.out.println("Great! I am thinking of an integer between 1 and 3. Guess what it is?");
if (guess == randomNum) {
System.out.println("Congradulations! You guessed correctly! The number was" + randomNum);
} else {
System.out.println("Sorry, your guess was incorrect. The number I was thinking of was" + randomNum);
}
} else {
System.out.println("Goodbye.");
}
}
}
この質問は、他の場所で回答されている場合ので、私は謝罪:
は、ここに私のコードです。
したがって、最初の「1」の後に別の入力が必要なプログラムを作成して、そのようにするのはなぜですか? – Tom