|
-
Feb 18th, 2002, 12:44 AM
#1
Thread Starter
Hyperactive Member
My First Java program :-)
Code:
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(false);
if (go ==null) {
go = new Thread(this);
go.start();
}
}
public void run() {
int quantity = Integer.parseInt(howMany.getText());
int numPrimes = 0;
//candidate: the number the number the might be prime
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[] arguments) {
FindPrimes fp = new FindPrimes();
}
}
-
Feb 18th, 2002, 02:40 PM
#2
Hyperactive Member
very nice
-
Feb 26th, 2002, 09:17 PM
#3
Fanatic Member
not bad, how long you been using java for ??
Some people have told me they don't think a fat penguin really embodies the grace of Linux, which just tells me they have never seen a angry penguin charging at them in excess of 100mph. They'd be a lot more careful about what they say if they had.
-- Linus Torvalds
[ Galahtech.com] | [ My Site] | [ Fishsponge] | [ UnixForum.co.uk]
-
Feb 27th, 2002, 12:32 PM
#4
Thread Starter
Hyperactive Member
-
Feb 28th, 2002, 03:16 PM
#5
Member
I like it a lot
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|