我正在为一个课堂项目创建一个“猜谜游戏”。这个想法是,用户将尝试猜测一个数字,而GUI将显示他们还剩下多少次尝试。 MyCustomTooHighException和MyCustomTooLowException都扩展了Exception。所以,我的问题是,每当我运行我的代码时,它似乎都要经过两次GuessCheckNumber方法,而且我不太确定为什么。
这是我的GuessTheNumberMethod:
public class GuessTheNumber extends JFrame{
public int random;
public int attempts;
//public int guess;
private String title;
public GuessTheNumber(){
attempts = 0;
}
public int checkGuess(int guess) {
Random rand = new Random();
random = rand.nextInt(100) +1;
MyCustomException tj = new MyCustomException();
try {
System.out.println(guess);
if (guess > random) {
throw new MyCustomTooHighException(guess);
} else if (guess < random) {
throw new MyCustomTooLowException(guess);
}
} catch (MyCustomTooHighException e) {
attempts++;
JOptionPane.showMessageDialog(null, "The value is smaller", "Alert", JOptionPane.ERROR_MESSAGE);
} catch (MyCustomTooLowException e) {
attempts++;
JOptionPane.showMessageDialog(null, "The value is bigger", "Alert", JOptionPane.ERROR_MESSAGE);
} finally {
if(guess == random)
{
JOptionPane.showMessageDialog(null, "You Won!", "Alert", JOptionPane.ERROR_MESSAGE);
}else if(guess != random && attempts<10)
JOptionPane.showMessageDialog(null, "Guess Again\nYou have "+ (10-attempts) +" attempts left." , "Alert", JOptionPane.ERROR_MESSAGE);
if(attempts ==10){
JOptionPane.showMessageDialog(null, "Game Over!", "Alert", JOptionPane.ERROR_MESSAGE);
}
return 10-attempts;
}
}
}
这是JPanel类:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
public class GuessGamePanel extends JPanel {
private GuessTheNumber guess;
JButton submitButton;
JTextField gField;
JLabel aField;
public GuessGamePanel(){
setLayout(new GridLayout(5,2));
setBackground(Color.lightGray);
guess = new GuessTheNumber();
add(new JLabel("Pick a number between 1 -10."));
add(new JLabel("Guess:"));
gField = new JTextField("0");
add(gField);
submitButton = new JButton("Submit");
add(submitButton);
submitButton.addActionListener(new ButtonListener());
aField = new JLabel();
add(new JLabel("Attempts Left:"));
add(aField);
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
int playsguess;
if(submitButton ==e.getSource()){
playsguess=Integer.parseInt(gField.getText());
guess.checkGuess(playsguess);
aField.setText(String.valueOf(guess.checkGuess(playsguess)));
}
}
}
}
行
guess.checkGuess(playsguess);
没有用,因为在下一行中再次调用该方法:
aField.setText(String.valueOf(guess.checkGuess(playsguess)));
只需删除第一行。