我必须创建一个程序,要求输入 1 到 10 之间的数字。生成一个 1 到 10 之间的随机数,如果我猜对了我的猜测数字并显示了密码,它应该输出。此外,如果我猜测的密码太高或太低,它应该输出。我必须joptionpane
在主类中使用在可实例化类中完成的计算和比较。我也必须使用else
and if-statement
s。我已经编写了代码,但是无论我选择什么数字,它都会输出 0 作为猜测的数字,它还告诉我即使我猜错了,我也猜对了。这是我写的两组代码。
import javax.swing.JOptionPane;
public class GuessApp{
public static void main(String args[]){
int guessNum, secretNum, correct, tooHigh, tooLow;
Guess myGuess;
myGuess = new Guess();
guessNum = Integer.parseInt(JOptionPane.showInputDialog(null,"Please enter a number between 1 and 10"));
myGuess.setGN(guessNum);
myGuess.compute();
guessNum = myGuess.getGuessNum();
secretNum = myGuess.getSecretNum();
tooHigh = myGuess.getTooHigh();
tooLow = myGuess.getTooLow();
correct = myGuess.getCorrect();
if (guessNum==correct){
JOptionPane.showMessageDialog(null,"Congratulations your number is"+guessNum+"and the secret number is"+secretNum+"you have won the game");
}
else if (tooHigh==guessNum){
JOptionPane.showMessageDialog(null,"I'm sorry you have guessed too high, your number is"+guessNum+"and the secret number is"+secretNum);
}
else if (tooLow==guessNum){
JOptionPane.showMessageDialog(null,"I'm sorry you guessed too low, your number is"+guessNum+"and the secret number is"+secretNum);
}
}
}
public class Guess{
private int guessNum, correct, tooHigh, tooLow, secretNum;
public Guess(){
guessNum = 0;
}
public void setGN(int guessNum){
this.guessNum = guessNum;
}
public void setSN(int secretNum){
this.secretNum = secretNum;
}
public void setCT(int correct){
this.correct = correct;
}
public void setTH(int tooHigh){
this.tooHigh = tooHigh;
}
public void setTL(int tooLow){
this.tooLow = tooLow;
}
public void compute(){
guessNum = guessNum;
secretNum = (int)(Math.random()*((10 - 1) +1)+1);
if ((secretNum<guessNum)){
guessNum = tooHigh;
}
else if ((secretNum>guessNum)){
guessNum = tooLow;
}
else if ((secretNum==guessNum)){
guessNum = correct;
}
}
public int getGuessNum(){
return guessNum;
}
public int getSecretNum(){
return secretNum;
}
public int getTooHigh(){
return tooHigh;
}
public int getTooLow(){
return tooLow;
}
public int getCorrect(){
return correct;
}
}
我刚刚开始了一个 java 类,所以我是新手。任何帮助将不胜感激。提前致谢。