Col*_*107 0 java loops for-loop
我的代码不会按我想要的方式执行.我println在actionPerformed类中放了一些语句,我认为它会在敌人循环结束时卡住,因为它只会通过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;
}
}
Run Code Online (Sandbox Code Playgroud)
for(int counter = 1; counter < 100_000; )
^^^
Run Code Online (Sandbox Code Playgroud)
你错过了迭代步骤,你应该增加counter(++counter).
另外,像你这样的长期阻塞任务不应该在EDT中执行,它应该拥有它自己Thread,因为你正在使用gui.