import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.*;
public class QuestionOne
{
private Label label;
private Button buttonOne;
private Button buttonTwo;
private Frame frame;
private List<Integer> list = new ArrayList<>();
QuestionOne()
{
init();
}
public static void main(String[] args)
{
new QuestionOne();
}
public void init()
{
frame = new Frame("Test");
frame.setBounds(300 , 100 , 600 , 500);
frame.setLayout(new FlowLayout());
//frame.setLayout(new GridBagLayout());
label = new Label();
buttonOne = new Button("生成20个随机数");
buttonTwo = new Button("求这20个随机数中质数的和");
frame.add(buttonOne);
frame.add(buttonTwo);
frame.add(label);
Events();
frame.setVisible(true);
}
private void Events()
{
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
buttonOne.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
generalRandomNumber();
}
});
buttonTwo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Integer numi = summation();
label.setText(numi + "");
}
});
}
private void generalRandomNumber()
{
//实例化随机数
Random random = new Random();
StringBuilder sb = new StringBuilder();
System.out.println("这20个随机数为:");
for (int i = 1; i <= 20; i++)
{
//随机产生1~1000之间的随机数
Integer n = random.nextInt(1000) + 1;
judgePrime(n);
//把值加入到label1中
//label.+= Convert.ToString(n) + " ";
if(n == 20)
sb.append(n + "");
else
sb.append(n + ",");
}
label.setText(sb.toString());
}
private boolean judgePrime(Integer number)
{
for (int i = 2; i < number; i++)
{
if (number % i == 0)
{ //上面的条件一旦城里说明被2和本身-1的数除尽了,不是质数,返回false
return false;
}
}
//循环执行完毕,也就说明上面的条件都不成立,说明是一个质数,返回true
list.add(number);
return true;
}
private Integer summation()
{
Integer num = 0;
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext())
{
Integer number = iterator.next();
num += number;
}
return num;
}
} |