希望它循环扔掉所有东西,直到用户输入正确的号码。当用户输错号码时,应该说“键入不同的号码”。当用户输入正确的号码时,应该说“祝贺你赢了”。 但在此之前,它会循环并说“键入不同的数字”,经过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);
}
}
}
答案 0 :(得分:3)
那是因为你唯一的迭代声明只显示&#34;你赢了!等等&#34;:
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!.."
}
}