2016-09-24 5 views
-3

私は比較的新しい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."); 
     } 
    } 
} 

この質問は、他の場所で回答されている場合ので、私は謝罪:

は、ここに私のコードです。

+0

したがって、最初の「1」の後に別の入力が必要なプログラムを作成して、そのようにするのはなぜですか? – Tom

答えて

0

ans1 = 1の場合、ユーザーからの別の入力を期待し、推測と別の入力が同じかどうかを確認するためです。

これは、生成された乱数を使用すると、二回目を追加した数に等しい場合、それは、それはあなたが正しく推測!おめでとう」が返されます、

 int guess = game.nextInt(); 

入力し、任意の数を待っていることを第2の入力があります!数は申し訳ありませんが、あなたの推測が間違っていた」他 『だった私は考えていた数は数

0

の代わりに』だった:。

int guess = game.nextInt(); 
System.out.println("Great! I am thinking of an integer between 1  and 3. Guess what it is?"); 

あなたは彼らにRを持っている必要があります逆転した。

System.out.println("Great! I am thinking of an integer between 1  and 3. Guess what it is?"); 
int guess = game.nextInt(); 
関連する問題