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!!!!
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("Primes Between 1 and " +MAX);
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 = primes = 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++)
for(int j = 2*i; j <= max; j = j + i)
primes[j] = false;
public static void displayPrimes(boolean primes)
int max = MAX;
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
Sorry, but those suggestions didn't work.
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
By codemonkey32 in forum C++
Last Post: 02-06-2006, 05:39 PM
Last Post: 12-19-2005, 06:10 AM
By premartha in forum C++
Last Post: 10-21-2005, 11:06 AM
By sparkette in forum Java
Last Post: 07-02-2005, 01:35 PM
By librypat in forum Java
Last Post: 07-16-2002, 12:03 PM
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center