Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Help With an Assignment

I have an assignment using the Sieve of Eratosthenes to identify prime numbers. The user will input the maximum number of array elements and the program will compute the prime numbers. The main method is required. How do I pass the user's input value to the computePrime method of the same class? THANKS FOR ANY INPUT YOU CAN PROVIDE!!!!

import java.io.*;
public class Lab13A100
{
public static void main(String args[])throws IOException
{
System.out.println("\nLAB13A 100 POINT VERSION\n");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the primes upper bound: ");
final int MAX = Integer.parseInt(input.readLine());
boolean primes[] = new boolean[MAX+1];
System.out.println("Computing Prime Numbers");
System.out.println("");
computePrimes(primes);
System.out.println("Primes Between 1 and " +MAX);
System.out.println("");
displayPrimes(primes);
}

public static void computePrimes(boolean primes[])// computes prime numbers
{
int max = MAX
//sets all numbers to primes
for(int i = 0; i <= max; i++)
primes[i] = true;
primes[0] = primes[1] = false;
// To compute all primes less than MAX, we need to rule out
// multiples of all integers less than the square root of max.
int n = (int) Math.ceil(Math.sqrt(max));
//For each integer i from 0 to n:
//If i is a prime, then none of its multiples are primes, so
//indicate this in the array by looping through its multiples
// noting they are not prime.
for(int i = 0; i <= n; i++)
{
if (primes[i])
for(int j = 2*i; j <= max; j = j + i)
primes[j] = false;
}
}
public static void displayPrimes(boolean primes[])
{
int max = MAX;
for(int i=0;i<=max;i++)
if (primes[i]==true)
System.out.print(i+" ");
}

}
[2086 byte] By [MRied] at [2007-11-11 8:02:17]
# 1 Re: Help With an Assignment
There doesn't seem to be anything wrong with your method calls, other than the fact that you use the same parameter name as the variable being passed into it. It will work but it's not a common practice.

I compiled your code and the main problem is that your MAX variable is stuck inside main which means displayPrimes() cannot access it. If you place MAX above main it will work. The only catch here is that you can't declare it final or else the user won't be able to give it a value.

Also, there was a missing ";" on one of the lines.

Hope this helps :)
srekcus at 2007-11-11 22:36:44 >
# 2 Re: Help With an Assignment
Sorry, but those suggestions didn't work.
MRied at 2007-11-11 22:37:38 >
# 3 Re: Help With an Assignment
srekcus's suggestions worked on my computer, the only hitch was MAX has to be declared static for the program to compile.

I did up to 200 and got all correct prime numbers:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199
Nathan87 at 2007-11-11 22:38:37 >