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 int[size];
for (int i = 0; i < size; i++) {
num[i] = in2 + i;
}
int[] order = new int[size];
boolean[] used = new boolean[size];
for (int i = 0; i < size; i++) {
int r = (int) ((size) * (Math.random()));
while (used[r]) {
r = (int) ((size) * Math.random());
}
order[i] = r; //fill array
used[r] = true; //r is now used
}
for (int i = 0; i < size; i++) {
if (num[order[i]] + num[order[i + 1]] > largestsum) {
largestsum = num[order[i]] + num[order[i + 1]];
}
}
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<size-1, like so…
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.