2016-03-15 64 views
0

我需要我的java代碼幫助!

要循環投擲一切,直到用戶輸入正確的數字。當用戶輸入錯誤的號碼時,應該說「輸入不同的號碼」。當用戶輸入正確的數字時,應該說「恭喜你贏了」。 但在那之前它會循環並說「輸入不同的數字」,並且在5次嘗試之後,我想讓它說「你沒有完成這項任務!你想再試一次嗎?」與我的隨機數猜遊戲存在問題

import javax.swing.*; 
import java.util.Random; 

public class Projekt_1 { 

    public static void main(String[] args) { 
     String number; 
     JOptionPane.showMessageDialog(null, "Welcome to the guessing game!" + "\nYou  gonna guess a number between 1 and 20." + "\nHOPE YOU LIKE IT!:)"); 

     Random amount = new Random(); 
     int guessnumber = anount.nextInt(20); 
     int random; 

     number = JOptionPane.showInputDialog("Guess a number between 1 and 20"); 
     random = Integer.parseInt(number); 

     while (random == guessnumber){ 
      JOptionPane.showMessageDialog(null, "You won!" + "\nYour number was" + "" + guessnumber);  
     } 

     if (random < guessnumber){ 
      number = JOptionPane.showInputDialog("Your number is to high :(" + "\nType in a new lower number!"); 
      random = Integer.parseInt(number); 
     }else if (random > guessnumber){ 
      number = JOptionPane.showInputDialog("Your number is to low :(" + "\nType in a higher number!"); 
      random = Integer.parseInt(number); 
     } 
    } 
} 

回答

3

那是因爲你只迭代語句只顯示「你贏了。等等!」:

while (random == guessnumber){  
    JOptionPane.showMessageDialog(null, "You won!" + "\nYour number was" + "" + guessnumber);  
} 

附上您的while循環下面的其他代碼,包括他們的內while循環。如果您的正確地縮進您的代碼,您應該能夠發現自己的問題。這是你在找什麼:

while (random != guessnumber){ 
    //prompt for user input 
    if (random < guessnumber){ 
     //Show Message "Your number is too low... 
    } 
    else if (random > guessnumber){ 
     //Show Message "Your number is too high..." 
    } 
    else{ //got the number 
     //Show Message "you won!.." 
    } 
} 
+0

你用「你贏了」永遠不會打,並用代碼是它只會進入一個繁忙的循環輸出相同的消息(因爲它從來沒有else塊獲得新的輸入) – Krease

+0

@Chris我簡化了解決方案的註釋,而不是長編碼,以提高可讀性。提示輸入是在我的代碼註釋'顯示消息「您的號碼太低...提示輸入」 '。即,自從op使用JOptionpane以來,他將同時顯示並提示。 – user3437460

+0

@Chris無論如何,我編輯它使它更清晰。 – user3437460