Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Why will this code fragment not run in Java?
Stared at this for hours and am so frustrated, please help:
public class PrimeNumbers {
public static void main (String[] args)
{
int endNum = 11;
boolean sieveArray[] = new boolean[endNum+1];
for (int i = 2; i < sieveArray.length; i++)
{
sieveArray[i] = true;
}
for (int i = 2; i < sieveArray.length; i++)
{
if (sieveArray[i] == true)
cancelMultiples(i, sieveArray);
}
System.out.print(sieveArray[1]);
}
public static void cancelMultiples(int prime, boolean[] sieveArray) {
for (int i = (2*prime); i <= sieveArray.length; i += prime)
{
if (i % prime == 0)
sieveArray[i] = false;
}
}
}
2 Answers
- ?Lv 610 years agoFavorite Answer
You have given true value to only elements 2 to 11
what about 0 and 1
so when in the last print statement you try to print element 1 it gives error
- PersonLv 710 years ago
It would help to know what error you're getting and where, but it looks like you're not even instantiating the first two boolean values in your array, yet you're trying to print out value 1. Java no like that.
Also, in your cancelMultiples class, you're running i to <= array length. Don't do that. You could go out of bounds.