2017-10-15 114 views
0

好吧,我知道這一個已被問過,但我只是無法弄清楚什麼是錯的。這裏是我的指令:Java隨機數猜對遊戲與對話框

「編寫一個程序,生成一個介於1到1000之間的隨機數,然後要求用戶猜測該數字是什麼,如果用戶的猜測高於隨機數,程序應顯示「太高,再試一次」。如果用戶的猜測低於隨機數,程序應該顯示「太低,再試一次」。程序應該使用一個重複的循環,直到用戶正確猜測隨機數
另外,保持猜測的次數的計數,用戶使得當用戶正確地猜測隨機數,程序應該顯示猜測的次數。 輸入和輸出應當與對話框和消息框來完成。「

我一直在工作和閱讀這一週,這是我的第二個化身。我處於所有閱讀都扭曲了頭的地步。我得到它要求在對話框中的數字,然後什麼都沒有。我錯過了什麼來保持循環?請解釋什麼和爲什麼。預先感謝您的期待。

import java.util.Scanner;  // Needed for the Scanner class. 
import java.util.Random;   // Needed for the Random class. 
import javax.swing.JOptionPane; // Needed for JOptionPane. 

/** 
This program generates a random number guessing game. 
*/ 

public class GuessingNumbersGame 
{ 
    public static void main(String[] args) 
    { 
// Create an object and assign a whole random number 
// from 1 to 1000 to it. 
     int rnumber;` 
     Random randomNumbers = new Random(); 
     rnumber = randomNumbers.nextInt(1000) + 1; 

// Ask the user to guess the random number. 
     String answer; 
     int guess; 
     answer = JOptionPane.showInputDialog("Enter a whole " + 
      "number between 1 and 1000."); 
     guess = Integer.parseInt(answer); 
     int guesses; 
     guesses = 0;               

// Create a loop of user guesses versus the random number 
// until the user answers correctly and keep track of the 
// number of times the user guesses. 
     while (guess != rnumber); 
     {         
      if (guess > rnumber) 
      { 
       JOptionPane.showMessageDialog(null,"Too high, try again."); 
       guess = Integer.parseInt(answer); 
       guesses++; 
      }    
      if (guess < rnumber) 
      {       
       JOptionPane.showMessageDialog(null,"Too low, try again."); 
       guesses++; 
      } 
     }  
     while (guess == rnumber) 
     {     
      guesses++; 
      JOptionPane.showMessageDialog(null,"Congratulations! The correct " + 
       "number is " + rnumber + ",and you had" + guesses + "guesses."); 

     } 

    System.exit(0); 
    } 
} 
+3

如果您希望人們嘗試閱讀,請正確縮進您的代碼。 – khelwood

回答

0

首先,更改while (guess == rnumber) {if(guess == rnumber) {,使其只執行一次。
至於你的問題的答案,你需要設置猜測和答案。
我會建議在控制檯中這樣做,這將設置回答java.util.Scanner.nextLine();,然後猜測是同樣的事情。在JOptionPanes上不太容易。

0

您的程序構建不正確。實現您被要求編寫的簡單算法的幾個重要問題。它可以(在這裏爲一些僞代碼)制定這樣:

begin 

guess <- 0 
guesses <- 0 
randnum <- new random number [1,1000] 
do 
    guess <- ask user input 
    guesses++ 
    if guess > randnum 
     show "Too high" 
    if guess < randnum 
     show "Too low" 
while guess != randnum 

congrats // guess = randnum 
show number of guesses 

end 

您的代碼不會這個樣子。檢查你的陳述,條件和循環。