这是我为课程创建的一个小游戏 - 工作正常除了如果猜测==数字,消息框没有显示,程序跳过它并转到下一个关于总猜测的消息等等...我的逻辑错了,但我很困惑。我觉得我已经尝试了一百万件事......任何帮助都会非常感激。
import java.util.Random;
import javax.swing.JOptionPane;
public class GuessingGameTestMyIdeas {
public static void main(String[] args) {
Random rand = new Random();
int number = rand.nextInt(32)+1;
int guessCount = 0; // total count variable
int lessCount = 0; // number of less than guesses
int moreCount = 0; // number of greater than guesses
String guessString = JOptionPane.showInputDialog("Guess the number I'm thinking of, between 1 and 32: ");
int guess = Integer.parseInt(guessString) ;
while (guess != number){ //run this loop while guess is not equal to the random number generated.
if (guess == number){
JOptionPane.showMessageDialog(null, "You guessed correctly");
} else if (guess < number){
lessCount = lessCount + 1;
String lowString = JOptionPane.showInputDialog("Your guess is too low. Next Guess:");
guess = Integer.parseInt(lowString);
} else {
moreCount = moreCount +1;
String highString = JOptionPane.showInputDialog("Your guess is too high. Next Guess:");
guess = Integer.parseInt(highString);
}
guessCount += 1; // after each guess, the guessCount goes up by one
}
String output = "Your total number of guesses is " + guessCount + " with " + lessCount + " smaller guesses " + moreCount + " larger guesses.";
JOptionPane.showMessageDialog(null, output);
答案 0 :(得分:0)
你必须移动
行JOptionPane.showMessageDialog(null, "You guessed correctly");
在while循环后面。
或者在while循环的末尾移动if,但第一个选项对我来说似乎更清楚。
你循环的条件是guess != number
,并且在你要求guess == number
之后。因此,这永远不会成真。当玩家猜对了,循环就会离开,而if claus也不会被再次评估。
顺便说一句:调试你的程序会向你展示。
答案 1 :(得分:0)
循环时将线条放在外面。
if (guess == number){
JOptionPane.showMessageDialog(null, "You guessed correctly");
}
我希望它有所帮助!!