[英]Having problems with my random number guess game
希望它循環播放所有內容,直到用戶輸入正確的數字為止。 當用戶輸入錯誤的數字時,應該說“輸入其他數字”。 當用戶輸入正確的數字時,應該說“恭喜您贏了”。 但是直到那之前,它會循環播放並說“輸入不同的數字”,經過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);
}
}
}
那是因為您唯一的迭代語句僅顯示“ You won!.. etc”:
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!.."
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.