Tuesday, October 11, 2011

Find prime number

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Findprimes extends JFrame implements Runnable, ActionListener{
Thread go;
JLabel howmanylabel=new JLabel("Quantity: ");
JTextField howmany=new JTextField("400",10);
JButton display=new JButton("Display primes");
JTextArea primes=new JTextArea(8,40);

Findprimes(){
super("Find prime Numbers");
setSize(400,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content=getContentPane();
BorderLayout bord=new BorderLayout();
content.setLayout(bord);
display.addActionListener(this);

JPanel topPanel=new JPanel();
topPanel.add(howmanylabel);
topPanel.add(howmany);
topPanel.add(display);

content.add(topPanel,BorderLayout.NORTH);
primes.setLineWrap(true);
JScrollPane textPane=new JScrollPane(primes);
content.add(textPane,BorderLayout.CENTER);
setVisible(true);
}
public void actionPerformed(ActionEvent evt){
display.setEnabled(true);
if(go==null){
go=new Thread(this);
go.start();
}

}
public void run(){
int quantity=Integer.parseInt(howmany.getText());
int numprimes=0;
int candidate=2;
primes.append("First "+quantity+" primes;");
while(numprimes<quantity){
if(isPrime(candidate)){
primes.append(candidate+" ");
numprimes++;
}
candidate++;
}
}
public static boolean isPrime(int checkNumber){
double root=Math.sqrt(checkNumber);
for(int i=2;i<root;i++){
if(checkNumber%i==0)
return false;
}
return true;
}
public static void main(String[] a){
Findprimes fp=new Findprimes();
}
}

No comments:

Post a Comment