这段几十行的JAVA作业小程序有俩BUG,跪求解答。
课程设计
1
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
public class Task1 extends JFrame implements ActionListener {
private JLabel word;
private JLabel[] animal;
private JButton checkbutton;
private JPanel jp1, jp2,jp3,jp4;
private JTextField ans;
private String answer;
private String coranswer;
public Task1() {
word=new JLabel("How many animals have come to the party?");
animal=new JLabel[10];
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
jp4 = new JPanel();
ans = new JTextField(2);
jp1.setLayout(new GridLayout(0,5));
jp2.setLayout(new BorderLayout());
jp3.setLayout(new FlowLayout());
jp4.setLayout(new FlowLayout());
this.setTitle("Welcome to the Jungle Party!");
checkbutton=new JButton("Check!");
jp4.add(checkbutton);
jp3.add(word);
jp3.add(ans);
jp2.add(BorderLayout.CENTER,jp3);
jp2.add(BorderLayout.SOUTH,jp4);
jp2.add(BorderLayout.NORTH,jp1);
this.makepic1();
this.getContentPane().add(jp2);
checkbutton.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocation(100,100);
this.setSize(1920,1080);
this.setVisible(true);
}
public void actionPerformed(ActionEvent event){
answer = ans.getText().trim();
while(!answer.equals("null"))
{
if (answer.equals(coranswer)){
word.setText("Correct!How many animals are in the party now?");
this.makepic2();
return;
}
else{word.setText("Wrong!Try again!");}
return;}
}
private void makepic1(){
for(int i=0;i<10;i++){
int j=i+1;
animal[i]=new JLabel(new ImageIcon(getClass().getResource("animal"+j+".png")));
jp1.add(animal[i]);
coranswer="10";
}
}
private void makepic2(){
jp1.removeAll();
double t =Math.floor(Math.random()*9 + 1);
int k= (int) t;
coranswer= String.valueOf(k) ;
for(int i = 0;i<k;i++)
{ int j = i + 1;
animal[i]=new JLabel(new ImageIcon(getClass().getResource("animal"+j+".png")));
jp1.add(animal[i]);
}
}
}
这段程序就是一开始显示10张图,在文本框里输入正确的数字(一开始固定是10)的话就会显示正确,然后随机再显示1-10个图片,错误的话就会告诉你错误让你重新输入,像这样无限循环。
现在有两个BUG,如果前后两次图片数正好随机成相等的话,不管输入多少都会显示错误(看起来是这种感觉)。如果在前一次输入正确的情况下,再次输入正确的话,图片文字都不会换,必须再按一下CHECK,文字显示错误了,图片同时会换(也就是说,必须是文字显示WRONG的情况下,输入正确的结果才能正常运行,如果是文字显示correct的情况下再次正确了,图片不换,必须先wrong了才行。)
用Eclipse多运行几次就知道这俩BUG是什么意思了。
发表回复