2013-02-20 94 views
-2

該應用程序是一個數字猜測遊戲,我的問題是當用戶獲得隨機數時,它會詢問用戶是否希望繼續,如果他鍵入「y」它會創建一個新的隨機數並要求用戶猜測它。它然後應該要求用戶「輸入一個數字」。相反,我得到無法從代碼中刪除一行?

「過高」(或 「過低」)
「輸入號碼」

EX輸出:
輸入號碼:
更正你得到它!號碼是2 你有2次嘗試。
你想再次玩(y/n):
y
太低!再試一次。
輸入號碼:

我該如何解決問題而不打印輸入數字後確定的「太高」或「太低」?

ps。我試了很多辦法,但我堅持:(

public static void main(String[] args) { 
    System.out 
      .println("Welcome to the gussing game, Try to guess the number am thinking of to win!"); 
    System.out 
      .println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); 
    System.out.println(); 

    System.out 
      .println("Am thinking of a number between 0 and 10. Try to guess it."); 
    System.out.println(); 

    Scanner sc = new Scanner(System.in); 
    String choice = "y"; 

    double rightNum = Math.random() * 10; 
    int randomNum = (int) rightNum; // convert the random number to int 
    int tries = 0; 

    while (!choice.equalsIgnoreCase("n")) { 

     System.out.println("Enter the Number:"); 
     int guess = sc.nextInt(); 
     tries++; 

     if (guess == randomNum) { 
      System.out.println("Correct you've got it! The Number Was " 
        + randomNum); 
      System.out.println("You got it in " + tries + " tries."); 
      System.out.println("Would you like to play again (y/n):"); 
      choice = sc.next(); 

      if (choice.equalsIgnoreCase("y")) 
      // reset the random number 

      { 
       rightNum = Math.random() * 10; 
       randomNum = (int) rightNum; 
       tries = 0; 

      } 
     } 

     if (guess > randomNum + 10) { 
      System.out.println("Way to high! Try again."); 
     } else if (guess < randomNum) { 
      System.out.println("Too low! Try again."); 
     } else if (guess > randomNum && guess <= randomNum + 10) { 
      System.out.println("Too high! Try again."); 
     } 

    } 

} 

}

+0

來吧!花5分鐘自行解決這個問題,你將學到的不僅僅是從這裏得到答案。你怎麼樣學習如何使用調試器進入你的代碼?然後你會看到你的程序出錯了,這很明顯。 – Mic 2013-02-20 03:41:12

回答

9
else if (guess > randomNum + 10) 
{ 
    System.out.println("Way to high! Try again."); 
} 

你錯過了別的出路。

+0

雅但是,並沒有真正解決我的問題 – babaysteps 2013-02-20 03:31:53

+0

@ user1852564怎麼樣?它對我來說工作正常 – MadProgrammer 2013-02-20 03:32:40

+0

它。否則,如果猜測==隨機,你會生成一個新的隨機數,但是猜測仍然有一個來自之前的值,並導致它落入隨後的一個if條件。 – Bizmarck 2013-02-20 03:35:45

0

更改此

{ 
    rightNum = Math.random() * 10; 
    randomNum = (int) rightNum; 
    tries = 0; 
} 

{ 
    rightNum = Math.random() * 10; 
    randomNum = (int) rightNum; 
    tries = 0; 
    continue; /* this goes back to while loop */ 
}