Fat*_*joy 5 java user-interface event-handling infinite-loop
我刚刚开始学习Java GUI并在练习事件处理时遇到了这个问题. 这是初始窗口
当我在文本字段中输入一个数字时,应该说出猜测的数字是更高,更低还是匹配.如果不匹配则会提示输入另一个号码.但是窗户就挂了. 输入数据后
我猜它落在一个无限循环中.这是代码.帮我找出问题所在.谢谢.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RandomNumGame extends JFrame {
private JLabel promptLabel, resultLabel, answerLabel;
private int tries=1, randomNum, guessNum;
private JButton button;
private JTextField txt;
private boolean guessed;
public RandomNumGame() {
setLayout(new FlowLayout());
promptLabel = new JLabel("Guess a number(1-1000): ");
add(promptLabel);
txt = new JTextField(7);
add(txt);
button = new JButton("Guess!");
add(button);
resultLabel = new JLabel("");
add(resultLabel);
/*answerLabel = new JLabel("");
add(answerLabel);
*/
Event e = new Event();
button.addActionListener(e);
}
private class Event implements ActionListener{
public void actionPerformed(ActionEvent e){
randomNum = (int )(Math.random() * 1000 + 1);
guessed=false;
do{
try{
guessNum = (int)(Double.parseDouble(txt.getText()));
if(guessNum>randomNum){
resultLabel.setText("Your number is higher. Try Again");
}
else if(guessNum<randomNum){
resultLabel.setText("Your number is lower. Try Again");
}
else{
resultLabel.setText("Your number matched!");
guessed=true;
}
}
catch(Exception ee){
resultLabel.setText("Enter a legit number. What are you stupid?");
}
}while(!guessed);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RandomNumGame ran = new RandomNumGame();
ran.setDefaultCloseOperation(EXIT_ON_CLOSE);
ran.setSize(300, 120);
//ran.pack();
ran.setVisible(true);
ran.setTitle("Random Number Game");
}
}
Run Code Online (Sandbox Code Playgroud)
您的方法中不需要 xc2xb4t 循环actionPerformed。只要让它执行一次,然后检查它是否被猜对了。当用户输入错误的号码时,您基本上就陷入了循环。为了使其更平滑,仅在guessedis时创建随机数true,并仅执行一次猜测和条件。
// Change constructor\npublic RandomNumGame() {\n ...\n guessed = true; // initialize to true to create a new number when you click\n}\nprivate class Event implements ActionListener{\n public void actionPerformed(ActionEvent e){\n if(guessed) { // If the number was guessed, on the next click you get a new random number\n randomNum = (int )(Math.random() * 1000 + 1);\n guessed = false;\n }\n try{\n guessNum = (int)(Double.parseDouble(txt.getText()));\n if(guessNum>randomNum){\n resultLabel.setText("Your number is higher. Try Again");\n }\n else if(guessNum<randomNum){\n resultLabel.setText("Your number is lower. Try Again");\n }\n else{\n resultLabel.setText("Your number matched! Click again for a new Number");\n guessed=true;\n }\n }\n catch(Exception ee){\n resultLabel.setText("Enter a legit number. What are you stupid?");\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n