2014-12-06 36 views
2

我已經編碼了一個簡單的隨機數發生器,你需要猜測它是什麼數字,但由於某種原因,如果輸入的數字是正確的,它將不會打印出來。有人可以看看這個嗎? IM Java中的小白順便說一句......學習自己..缺少'你的號碼是正確的'句子

package randomnumbergenerator; 
import java.util.Random; 
import java.util.Scanner; 

public class main { 
    public static void main(String args[]) 
    { 
     System.out.println("Enter the lowest border"); 
     Scanner scannerx = new Scanner(System.in); 
     int y = scannerx.nextInt(); 
     System.out.println("Enter the highest border"); 
     Scanner scannery = new Scanner(System.in); 
     int x = scannery.nextInt(); 
     Random random = new Random(); 
     int randomnummer = random.nextInt(x) + y; 
     System.out.println("Now try to guess the number!"); 
     Scanner guessingnumber = new Scanner(System.in); 
     int guessednumber = guessingnumber.nextInt(); 
     while(randomnummer != guessednumber){ 
      if (randomnummer == guessednumber){ 
      System.out.println("you guessed it right!"); 
      } 
      if(randomnummer >= guessednumber){ 
      System.out.println("the number you guessed it wrong, its higher!"); 
      } 
      if(randomnummer <= guessednumber){ 
      System.out.println("the number you guessed it wrong, its lower!"); 
      } 
      System.out.println("try again!"); 
      Scanner guessingnumber1 = new Scanner(System.in); 
      guessednumber = guessingnumber1.nextInt(); 
     } 
    } 

} 在此先感謝!

+3

您開擴新的'Scanner'每次土特產品想讀的東西......這是沒有必要的,使用單一的一個 – Dici 2014-12-06 22:13:34

+0

我必須這樣做,因爲我想每次放入其他東西時不會遇到這種情況 – 2014-12-06 22:59:35

+0

是的,但您可以重複使用相同的'Scanner'幾次! – Dici 2014-12-06 23:07:52

回答

6

您的線路if (randomnummer == guessednumber){位於while(randomnummer != guessednumber)的while循環內。這兩個條件不能同時存在,所以if條件永遠不會滿足。

您可以將「您猜對了」消息移至while循環結束後。

+0

我想我也會提到檢查大於或小於的條件應該是'>'和'<'而不是'> ='和'<=' – cschieb 2014-12-06 22:33:11

0

試試這個

while(randomnummer != guessednumber){ 

    if(randomnummer > guessednumber){ 
     System.out.println("the number you guessed it wrong, its higher!"); 
    } else { 
     System.out.println("the number you guessed it wrong, its lower!"); 
    } 
    System.out.println("try again!"); 
    Scanner guessingnumber1 = new Scanner(System.in); 
    guessednumber = guessingnumber1.nextInt(); 
} 

System.out.println("you guessed it right!");