How do I overcome java.lang.ArrayIndexOutOfBoundsException: 2 in this code?

The last for loop will overflow when i=size-1.

Up vote 0 down vote favorite share g+ share fb share tw.

When I tested this code, it gave me java.lang. ArrayIndexOutOfBoundsException: 2 The code isn't finished yet but this is what I am trying to do: A program that asks the user for two numbers. Print all numbers from the smaller number to the larger number (inclusive) in a random order.

Using this order, find the largest sum of 2 numbers adjacent to one another. Could some please point out to me what needs to be fixed as well as how to fix it? Thanks.

Boolean isNum = false; int in1 = 0; int in2 = 0; int size = 0; int largestsum = 0; while (!isNum) { try { System.out. Print("Enter a number: "); in1 = Integer. ParseInt(in.readLine()); boolean isSame = false; while (!isSame) { System.out.

Print("Enter a number: "); try { in2 = Integer. ParseInt(in.readLine()); if (in1! = in2) { isSame = true; } else { System.out.

Println("Same number. "); } } catch (NumberFormatException nfe) { System.out. Println("Not a number.

"); } } isNum = true; } catch (NumberFormatException nfe) { //catches error System.out. Println("Not a number. "); //informs user of the error } } if (in1 > in2) { size = in1 - in2 + 1; int num = new intsize; for (int I = 0; I largestsum) { largestsum = numorderi + numorderi + 1; } } java arrays for-loop while-loops boolean link|improve this question asked Mar 24 at 2:42user1215225213 100% accept rate.

The last for loop will overflow when i=size-1 In your question, you want to get the sum between 2 adjacent numbers. Your logic in the last for loop says that you calculate the sum by adding number I to i+1. The last item in your array is at position size-1, so when you then try to add this to the next adjacent number, (size-1)+1 overflows the array.

To fix the problem, your last for loop should only continue until I largestsum) { largestsum = numorderi + numorderi + 1; } } With this fixed logic, the largest item in the for loop is size-2, and when you add 1 to it (for the next adjacent number), it will choose item (size-2)+1, which is the last item in the array, rather than overflowing the array.

My guess is the problem is in your very last for loop. Since order can contain values ranging from 0 to size, numorderi is always valid, but in the case where orderi==size, numorderi+1 is out of bounds.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions