This discussion is archived
9 Replies Latest reply: May 14, 2007 1:44 PM by 807606

# ArrayIndexOutOfBoundsException error

Currently Being Moderated
Hi, I can successfully compile and run my program for inputs from 2-9, however when I input 10 as the parameter argument I receive the following error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -2146737495
at FactorFinder.<init>(FactorFinder.java:36)

Here are those two particular lines:

line 36 (bold):

sieve = new boolean[(int)maxVal + 1];
for (int i = 2; i <= maxVal; i++)
sieve[i] = true;

// mark non-primes <= N using Sieve of Eratosthenes
// for (int i = 2; i*i <= maxVal; i++) {
for (int i = 2; i <= maxVal; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (sieve){ // if not marked already{
primeCount++;
for (int j = i; i*j <= maxVal; j++){
sieve[i*j] = false;
}
}
}

line 61 (bold):

try
{
String retVal = "";
while (true)
{
retVal = cdr.nextConsecutiveDigits();
//                         System.out.println("got Value " + retVal);
if (!retVal.equals("null")) {
double N = Math.sqrt(Double.parseDouble(retVal));
N = Math.ceil(N);
//                              System.out.println("maxVal " + N.longValue());
if (new FactorFinder((long)N).getFactor(Long.parseLong(retVal)) == 1)
{
System.out.println("Prime was found: " + retVal);
break;
}
}

sorry for the formatting... any help will be greatly appreciated.

• ###### 1. Re: ArrayIndexOutOfBoundsException error
Currently Being Moderated
The first thing I'd do before anything else is change any and all for-loops that state:
``            for (int foo = 0; foo <= maxFoo; foo++)``
to a for-loop that states this:
``            for (int foo = 0; foo < maxFoo; foo++)``
Often if you use <= as the end criteria of a for loop you end up bumping against the top of some array and going out of bounds. If it still doesn't work, come back. but next time, please use code tags.

/Pete
• ###### 2. Re: ArrayIndexOutOfBoundsException error
Currently Being Moderated
Thanks for your response. However, I need it to be <= maxVal because I need it to include maxVal. Does this make sense? Is there anything else that could be causing the problem?

Thanks again.
• ###### 3. Re: ArrayIndexOutOfBoundsException error
Currently Being Moderated
Thanks for your response. However, I need it to be <=
maxVal because I need it to include maxVal.
Still if you change your loops to use < instead of <=, does the exception go away? If so, you have to fix your program logic. Consider increasing your maxvalue by one but keeping the "<".

Another thing, put in a try / catch block and System.out.println the values of your indices from within the catch block. You'll see what the culprit is.
• ###### 4. Re: ArrayIndexOutOfBoundsException error
Currently Being Moderated
They actually are both in try/catch blocks, and I did try what was recommended earlier by increasing maxVal by one and making it < instead of <=.

But still no luck. Same error!!! Any other suggestions?
• ###### 5. Re: ArrayIndexOutOfBoundsException error
Currently Being Moderated
But still no luck. Same error!!! Any other
suggestions?
Can you show us the rest of your code, the smallest self-contained, compilable example that demonstrates your problem. But this time, please use code formatting. It makes it so much easier to read code.
Compare this:

//// code
private void resetButtons()
{
turnedOverBtn = null;
ArrayList<String> btnCharsArrayList = new ArrayList<String>();
for (char myChar = 'A'; myChar < 'A' + (buttonCount / 2); myChar++)
{
// add each character in duplicate. This fills the arrayList w/
// the characters 'A', 'A', 'B', 'B', ... up to the number of buttons
// notice for loop goes up to buttonCount / 2
}

Random myRand = new Random();
for (int col = 0; col < MAXCOL; col++)
{
for (int row = 0; row < MAXROW; row++)
{
int btnNumb = col * MAXROW + row;
String visibleText = "Btn " + btnNumb;

// get a random number to randomly select a letter:
// as ArrayList gets smaller, the number of possible randomints
// gets smaller automatically
int randomInt = myRand.nextInt(btnCharsArrayList.size());
String hiddenText = btnCharsArrayList.get(randomInt);

// remove letter once we use it.
btnCharsArrayList.remove(randomInt);

// set our button w/ both hidden and visible text
buttonGrid[row][col].setHiddenText(hiddenText);
buttonGrid[row][col].setVisibleText(visibleText);
buttonGrid[row][col].setActive();
}
}
}

with this
``````    private void resetButtons()
{
turnedOverBtn = null;
ArrayList<String> btnCharsArrayList = new ArrayList<String>();
for (char myChar = 'A'; myChar < 'A' + (buttonCount / 2); myChar++)
{
// add each character in duplicate.  This fills the arrayList w/
// the characters 'A', 'A', 'B', 'B', ... up to the number of buttons
// notice for loop goes up to buttonCount / 2
}

Random myRand = new Random();
for (int col = 0; col < MAXCOL; col++)
{
for (int row = 0; row < MAXROW; row++)
{
int btnNumb = col * MAXROW + row;
String visibleText = "Btn " + btnNumb;

// get a random number to randomly select a letter:
// as ArrayList gets smaller, the number of possible randomints
// gets smaller automatically
int randomInt = myRand.nextInt(btnCharsArrayList.size());
String hiddenText = btnCharsArrayList.get(randomInt);

// remove letter once we use it.
btnCharsArrayList.remove(randomInt);

// set our button w/ both hidden and visible text
buttonGrid[row][col].setHiddenText(hiddenText);
buttonGrid[row][col].setVisibleText(visibleText);
buttonGrid[row][col].setActive();
}
}
}``````
and you tell me which is easier to read.

Good luck! /Pete
• ###### 6. Re: ArrayIndexOutOfBoundsException error
Currently Being Moderated
``````public class GooglePuzzle
{
// YOUR COMMENT HERE: describe at a high-level what main does
public static void main(String[] args) {
// YOUR CODE GOES HERE
/*         try
{
if(args.length < 2)
{
System.out.println("Usage: GooglePuzzle <width name of .txt file>");
System.exit(1);
}
}
catch(FileNotFoundException fnf)
{
System.out.println(fnf.getMessage());
System.exit(1);
}
*/
Reader fr = null;

try
{
fr = new FileReader(args[1]);
if(args.length < 2)
{
System.out.println("Usage: GooglePuzzle <num-digits> <file-name>");
System.exit(1);
}
}
catch (IOException e)
{
System.out.println(e.getMessage());
//            e.printStackTrace();
}

try
{
String retVal = "";
while (true)
{
retVal = cdr.nextConsecutiveDigits();
//                         System.out.println("got Value " + retVal);
if (!retVal.equals("null")) {
double N = Math.sqrt(Double.parseDouble(retVal));
N = Math.ceil(N);
//                              System.out.println("maxVal " + N.longValue());
if (new FactorFinder((long)N).getFactor(Long.parseLong(retVal)) == 1)
{
System.out.println("Prime was found: " + retVal);
break;
}
}
else
{
System.out.println("Could not find a prime of length");               // Fix print statement
break;
}
//            new FactorFinder(Long.parseLong(retVal)).getFactor(Long.parseLong(retVal));
}
}
catch (IOException io)
{
System.out.println(io.getMessage());
//               io.printStackTrace();
}
catch (NumberFormatException e)
{
System.out.println("Number formatting error: " + e.getMessage());
}
}
}``````
AND
``````public class FactorFinder
{
// YOUR INSTANCE VARIABLE/VARIABLES HERE

boolean[]sieve;
int primeCount=0;
int primeIndex=0;
int[] primes;
// creates a FactorFinder valid for getting the smallest prime factor of
// any number less than or equal to maxVal
public FactorFinder(long maxVal) {
// YOUR CODE GOES HERE
sieve = new boolean[(int)maxVal + 1];
for (int i = 2; i <= maxVal; i++)
sieve[i] = true;

// mark non-primes <= N using Sieve of Eratosthenes
//        for (int i = 2; i*i <= maxVal; i++) {
for (int i = 2; i < maxVal+1; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (sieve){ // if not marked already{
primeCount++;
for (int j = i; i*j < maxVal+1; j++){
//      System.out.println("i="+i+" j="+j+" i*j = "+(i*j));
sieve[i*j] = false;
}
}
}

primes = new int[primeCount];
// System.out.println("Prime Count is "+primeCount);
// System.out.println("Prime Length is "+primes.length);
for (int i=2;i<=maxVal;i++){
if (sieve[i]){
//           System.out.println("Primes["+primeIndex+"]="+i);
primes[primeIndex]=i;
primeIndex++;
}
}

}

Please help, don't have much time left!! Thanks again. ``````
• ###### 7. Re: ArrayIndexOutOfBoundsException error
Currently Being Moderated
Your code doesn't compile. It's missing ConsecutiveDigitReader class code and FactorFinder.getFactor method.
• ###### 8. Re: ArrayIndexOutOfBoundsException error
Currently Being Moderated
Yes, I didn't include those here... didn't think you wanted to see that code?
• ###### 9. Re: ArrayIndexOutOfBoundsException error
Currently Being Moderated
You need to provide a compact compilable example for me and most others here to see any bugs.