我正在用java编写我的第一个程序。我在7年级。我无法弄清楚为什么我的“猜测按钮”不起作用。我的调试器说
“AWT-EventQueue-0”java.lang.NumberFormatException
我的输入字符串是""
public class GuessingGame extends JFrame
{
private JTextField txtGuess; // text field for the user's guess
private int theNumber; //the number we're trying to guess
private JTextField textField;
public void checkGuess() { // method/function to check too high or too low
// get the user's guess
String guessText = txtGuess.getText();
String message = "";
// check the user's guess for too low/too high
int guess = Integer.parseInt(guessText);
// too high
if (guess > theNumber)
{
message = guess + " was too high. Guess again!";
lblOutput.setText(message);
}
// too low
else if (guess < theNumber)
{
message = guess + " was too low. Guess again!";
lblOutput.setText(message);
}
else
{
message = guess + " was right! You win! Let's play again! ";
lblOutput.setText(message);
newGame();
}
}
public void newGame(){ // create a new random number 1..100
theNumber = (int)(Math.random() * 100 + 1);
}
public GuessingGame() {
getContentPane().setLayout(null);
...
txtGuess = new JTextField();
panel.add(txtGuess);
txtGuess.setColumns(10);
textField = new JTextField();
textField.setBounds(366, 18, 71, 22);
panel.add(textField);
textField.setColumns(10);
JButton btnGuess = new JButton("Guess!");
btnGuess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
checkGuess();
}
});
btnGuess.setBounds(195, 159, 97, 25);
...
}
...
我不知道导致错误的原因。
答案 0 :(得分:0)
我不建议你的代码。你应该切换案例或设计模式。
解决方法:
public void checkGuess() { // method/function to check too high or too low
// get the user's guess
String guessText = txtGuess.getText();
String message = "";
if(guessText.isEmpty()){
return;
}
...
答案 1 :(得分:0)
根据您提供的代码,我能得到的唯一结论是您不检查变量“guessText”。
在Integer.parseInt(string s)方法中,字符串中的字符必须全部为十进制数字。 @source docs.oracle
所以:
if ( !guessText.isEmpty()){
rest of the code
} else {
message = "The guess cannot be empty :(";
lblOutput.setText(message);
}
希望这有帮助。如果这不起作用。我需要更多代码输入。