我的代码不会按照我想要的方式执行。我在整个 actionPerformed 类中放置了一些println
语句,我认为它卡在了 foe 循环的末尾,因为它只通过 if 语句一次。我可能忽略了一些巨大的东西,你能看到有什么问题吗?
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class Frame extends JFrame implements ActionListener{
public JPanel contentPane;
public int yesNum, noNum;
public JProgressBar progressBar;
// ######### CONFIG ##########
public int genNum = 100_000;
//Edit genNum to change number of tries
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.apple.laf.AquaLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame frame = new Frame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Frame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 300, 195);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lab = new JLabel("Click to generate " + genNum + " times");
lab.setHorizontalAlignment(SwingConstants.CENTER);
lab.setBounds(5, 5, 289, 16);
contentPane.add(lab);
JButton b = new JButton("Generate");
b.setIcon(new ImageIcon("/Users/Colby/Desktop/checl.png"));
b.setActionCommand("Generate");
b.setBounds(80, 33, 139, 36);
contentPane.add(b);
JLabel yesLab = new JLabel("Yes Number: " + yesNum);
yesLab.setBounds(22, 81, 117, 16);
contentPane.add(yesLab);
JLabel noLab = new JLabel("No Number: " + noNum);
noLab.setBounds(22, 109, 117, 16);
contentPane.add(noLab);
progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBar.setBounds(5, 141, 289, 20);
progressBar.setMaximum(genNum);
contentPane.add(progressBar);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
Random rand = new Random();
int num = rand.nextInt(1);
int yesCounter = 0;
int noCounter = 0;
for(int counter = 1; counter < 100_000;){
if(num == 0){
System.out.println("testing yes");
yesCounter++;
System.out.println(counter+ ": Yes");
progressBar.setValue(counter);
} else if(num == 1){
System.out.println("testing no");
noCounter++;
System.out.println(counter+ ": No");
progressBar.setValue(counter);
}
num = rand.nextInt();
}
yesCounter = yesNum;
noCounter = noNum;
}
}