help with arrays: value of primes
Hello all,
I have a project that I have to do for my java course, and the instructor has explicitly stated that the info is not in the book. I have tried googling and other research methods, but I am completely stuck. Here is what I need to do:
50 points - Not in the book - (Exceptions, Arrays and Methods) Write a windows application named Primes . Create an array that will store 1000 boolean values indexed from 0 to 999. If the value at a particular index is true then the index value of the array is prime, if false then the index value of the array is not prime. Your windows app should allow the user to specify a range of primes to print to a rich un-editable textfield using user input into two text fields. You need to throw an exception if the user enters a number not within 0-999. Also handle the exception if the user types in a value that is not a number. The user will click a button and the information will then be displayed in the un-editable textfield (.NET - RichTextBox, Java - JTextArea) each prime separated by a tab. You need to write methods to set the array, to print the values to the rich textfield based upon the desired range. Use Message Boxes to display any error messages produced by the program.
I've got the array declared, but that's all I've been able to figure out:
int array[] = new int [1000];
Any help, and/or, pointers to where to figure this out, would be greatly appreciated!
Thanks so much!
Kal
[1493 byte] By [
Kal_025a] at [2007-11-26 21:10:34]

Are you sure you don't want the array to be:
boolean array[ ] = new boolean[1000]
?
I'd iterate through the array, then set all the values in the array to false but every prime numbered index to true.
Do you know how to get prime numbers? I'd find an algorithm on google for it. I know that if P is prime 2(P)+1 is also prime. I know that if P is even, then P is not prime. That doesn't cover everything though.
Message was edited by:
shlumph
Your instructor has pretty well told you what you need to create. Your job is to create the code, and earn the credit - if we create it, is it fair that you get the credit? Get started, and if you have a specific problem and question, pose the question here. Someone will give a nudge in the correct direction.
Hint: break the problem into separate pieces, and consider how each piece interacts with the others. Could each piece be a class?
Chuck,
I think you misunderstood me. I wasn't looking for someone to tell me the code, just an idea of where to start. I appreciate the hint also.
Here is what I've got now. I believe I have all the code right, but I'm getting an error saying 'class' or 'interface' expected. When I run it, it also can't find a main method, but it's in here, towards the bottom. Any help would be greatly appreciated.
Thanks,
Kal
/*
* Primes.java
*
* Created on March 13, 2007, 6:23 AM
*/
package Primes.UI;
/**
*
* @author Kal
*/
public class Primes extends javax.swing.JFrame {
/** Creates new form Primes */
public Primes() {
initComponents();
initArray();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Insert First Number:");
jLabel2.setText("Insert Second Number:");
jLabel3.setText("Primes in range:");
jButton1.setText("Calculate Primes");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Clear");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Exit");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton3)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel3)
.addComponent(jLabel1)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE)
.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE))))
.addGap(48, 48, 48))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2)))
.addGap(19, 19, 19)
.addComponent(jButton3)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// Array to hold 1000 integers (indexed 0-999)
int hi;
int lo;
//declare String variables
String num1, num2, result;
//retrieve integers from text fields
num1 = jTextField1.getText();
lo = Integer.parseInt(num1);
num2 = jTextField1.getText();
hi = Integer.parseInt(num2);
displayPrimes(lo, hi);
}
void displayPrimes(int lo, int hi) {
int i;
for (i = lo; i <= hi; i++) {
if (arr = true)
jTextField3.setText (jTextField3.getText() + i + " ");
}
}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Primes().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
// End of variables declaration
void initArray()
{
int i;
int n = 2;
for (i = 0; i < 1000; i++)
arr = true;
while (n <= 31) {
for (i = n*n; i <= 1000; i += n);
arr = false;
n++;
while (arr [n] != true)
n++;
}
}
>I know that if P is> prime 2(P)+1 is also prime. Perhaps not that relevant to the problem at hand, but this algorithm certainly can't be correct. 7 and 13 (as P) are both easy counter-examples.
That doesn't always work. Take 17 (prime) *2 = 34, + 1 = 35 (not prime) This is just one example. Thanks for the thought though.Kal
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
> Hello all,
> I have a project that I have to do for my java
> course, and the instructor has explicitly stated that
> the info is not in the book. I have tried googling
> and other research methods, but I am completely
> stuck. Here is what I need to do:
> 50 points - Not in the book - (Exceptions, Arrays and
> Methods) Write a windows application named Primes .
> Create an array that will store 1000 boolean values
> indexed from 0 to 999. If the value at a particular
> index is true then the index value of the array is
> prime, if false then the index value of the array is
> not prime.
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Ok DrLaszloJamf - that's a little scary.
Message was edited by:
tsith
Well, if you really don't know how to handle the primes "testing", something simple for start in algorithms about primes... have you ever heard about Eratosthenes' sieve? ;) Try to find this in wikipedia or somewhere and you'll got some clue..
> Well, if you really don't know how to handle the
> primes "testing", something simple for start in
> algorithms about primes... have you ever heard about
> Eratosthenes' sieve? ;) Try to find this in wikipedia
> or somewhere and you'll got some clue..
I think there's a link to this posted somewhere...
Heres a brute force method:
public class PrimeFinder{
public static void main(String[] args){
new PrimeFinder();
}
public PrimeFinder(){
findPrimes();
}
public void findPrimes(){
primes = new boolean[SIZE];
for(int i = 0; i < primes.length; i++){
primes[i] = false;
}
primes[1] = true; // 2 = prime
primeCount = 1;
long startTime = System.currentTimeMillis();
for(int i = 3; i <= primes.length; i += 2){
if(isPrime(i)){
primeCount ++;
primes[i-1] = true;
System.out.println("Prime #" + (primeCount) + ": " + (i));
}
}
long endTime = System.currentTimeMillis();
System.out.println("Found " + (primeCount) + " primes in " + (endTime - startTime) + " ms");
}
public boolean isPrime(int number){
int limit = (int)Math.sqrt((double)number);
for(int i = 3; i <= limit; i += 2){
if(number % i == 0){
return false;
}
}
return true;
}
boolean[] primes;
int primeCount = 0;
int SIZE = 1000;
}
Hello all,
First of all let me say thank you all for your help, it is very much appreciated.
I have been trying to sort this out for over a month which has put me way behind in my class. I have reworked it quite a bit and I think it is good, with one exception. For the line javax.swing.JTextField jTextField1.SetText( i + "\n" );
I keep getting a "; expected" error. Here is the entire code. I would greatly appreciate any help.
/*
* NewJFrame.java
*
* Created on March 10, 2007, 1:55 PM
*/
package primes;
/**
*
* @author Owner
*/
public class NewJFrame extends javax.swing.JFrame {
boolean arr[] = new boolean[1000];
/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
initArray();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jTextField3 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Number 1:");
jLabel2.setText("Number 2:");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
jButton1.setText("Find Range");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Exit");
jTextField3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField3ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jButton1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton2)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(layout.createSequentialGroup()
.addGap(52, 52, 52)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(46, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addGap(42, 42, 42)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// Array to hold 1000 integers (indexed 0-999)
int hi;
int lo;
//declare String variables
String num1, num2, result;
//retrieve integers from text fields
num1 = jTextField1.getText();
lo = Integer.parseInt(num1);
num2 = jTextField1.getText();
hi = Integer.parseInt(num2);
displayPrimes(lo, hi);
}
void displayPrimes(int lo, int hi) {
int i;
for (i = lo; i <= hi; i++) {
if (arr = true)
jTextField3.setText (jTextField3.getText() + i + " ");
}
}
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
// End of variables declaration
void initArray()
{
int i;
int n;
// good stuff
for (i = 0; i < 1000; i++)// turn all number prime
arr = true;
for (n=4; n < 1000; ++n)// loop trough 4... 1000 looking for non-primes
{
for (i =2; i <= n/2; ++i)// loop 2 ... n /2
{
if (n % i == 0){// if remainder is zero we found a non-prime
arr[n] = false;// mark as non-prime
break;// leave this loop
}
}
}
/*
while (n <= 31)
{
for (i = n*n; i <= 1000; i += n);
arr = false;
n++;
while (arr [n] != true)
n++;
} perhaps not good stuff */
for ( i = lo; i <= hi; ++i ) {
if(arr == true)
javax.swing.JTextField jTextField1.SetText( i + "\n" );
}
}
}
Thanks again,
Kal
