Two numbers in array
I want to get two numbers whose product is equal to a given number. Below is my code but it throws an ArrayIndexOutOfBoundsException
and I don't know why.
package com.sample;
public class ProductCheck {
public static void main(String[] args) {
// TODO Autogenerated method stub
int numArray[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int temp = numArray[0];
for (int i = 0; i <= numArray.length; i++) {
if (temp * numArray[i + 1] == 27) {
System.out.println("The two numbers are " + temp + " and " + numArray[i + 1]);
} else {
temp = numArray[i + 1];
}
}
}
}
In this case it should print 3
and 9
as the product of these two numbers is equal to 27
, but it doesn't work. Could anybody please point out why? Thanks in advance.
2 answers

Your algorithm is incorrect, because it would never find a pair unless its members are at adjacent indexes. In other words, if you look, say, for 30, it would find 5 and 6, because they are next to each other; however, it wouldn't find 3 and 9, because there are other numbers between them.
To solve this problem correctly, you need two nested loops: one to pick the first number, and the other one to pick the second number to be multiplied. Then you would check the product in the inner loop, and print the result if the match is found.
for (int i = 0 ; i != numArray.length ; i++) { for (int j = i+1 ; j != numArray.length ; j++) { // Use i and j as indexes of the two numbers to be multiplied. // Do your checking here, and print the result. } }
Note: You get
ArrayIndexOutOfBoundsException
because your loop condition is incorrect: the loop should stop when you reachnumArray.length1
, because you accessnumArray[i + 1]
. 
The exception occurs because your
i
loops from 0 tonumArray.length
, which is 10. But as you may know, arrays are zero based, so the largest index is 9. Putting10
in there will certainly throw an exception. Looping tonumArray.length  1
doesn't work either because you are accessingi + 1
, which will be 10 again. So you neednumArray.length  2
for it to not throw an exception.Not throwing an exception doesn't mean it outputs the right thing though. You seem to be only looking at number pairs like (4,5), (5,6) etc. You will never check
3,9
like this.Another approach is to output as soon as you find a number that is divisible by 27:
for (int i = 2 ; i < 27 ; i++) { if (27 % i == 0) { System.out.println("Found the two numbers: " + i + " and " + 27 / i); break; } }