我是Java的新手,我正在写这个简短的程序,您在其中猜测1到10之间的数字。正确的数字存储为整数。如果您猜中一个较低的数字,它应该说“正确的数字是较高的”,如果您猜中一个较高的数字,它应该说“正确的数字是较低的”。这是我所拥有的:
import javax.swing.*;
public class Oppg3 {
public static void main(String[] args) {
int number = 7;
int guessed = Integer.parseInt(JOptionPane.showInputDialog("Guess a number between 1 and 10"));
while(guessed>number) guessed = Integer.parseInt(JOptionPane.showInputDialog(guessed + " is wrong. Try a lower number."));
while(guessed<number) guessed = Integer.parseInt(JOptionPane.showInputDialog(guessed + " is wrong. Try a higher number."));
JOptionPane.showMessageDialog(null, guessed + " is correct!");
}
}
所以很显然,这是行不通的,因为如果您输入一个较小的数字,它将跳至下一个数字,即使输入较高的数字也将显示为正确。那么,如何解决此问题,以便检查两个语句?对不起,不好解释。谢谢。
最佳答案
最简单的解决方案是用if
替换当前的while,然后将它们都包含在
while(guessed!=number)
{
if(guessed>number) //stuff
if(guessd<number) //otherstuff
}