我想得到两个数字,其乘积等于给定数字。下面是我的代码,但它会抛出一个ArrayIndexOutOfBoundsException
,但我不知道为什么。
package com.sample;
public class ProductCheck {
public static void main(String[] args) {
// TODO Auto-generated 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];
}
}
}
}
在这种情况下,它应该打印3
和9
,因为这两个数字的乘积等于27
,但它不起作用。任何人都可以指出为什么?提前谢谢。
答案 0 :(得分:2)
您的算法不正确,因为除非其成员位于相邻索引,否则它永远不会找到一对。换句话说,如果你看30,它会找到5和6,因为它们彼此相邻;但是,它不会找到3和9,因为它们之间还有其他数字。
要正确解决此问题,您需要两个嵌套循环:一个用于选择第一个数字,另一个用于选择要乘以的第二个数字。然后,您将检查内循环中的产品,并在找到匹配项时打印结果。
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.
}
}
注意:由于您的循环条件不正确,您获得ArrayIndexOutOfBoundsException
:当您到达numArray.length-1
时,循环应该停止,因为您访问numArray[i + 1]
。
答案 1 :(得分:0)
发生异常是因为你的i
从0循环到numArray.length
,即10。但是你可能知道,数组是基于零的,所以最大的索引是9.放{{1}肯定会抛出异常。循环到10
无法正常工作,因为您正在访问numArray.length - 1
,这将再次为10。所以你需要i + 1
才能抛出异常。
不抛出异常并不代表它输出正确的东西。你似乎只是在看(4,5),(5,6)等数字对。你永远不会像这样检查numArray.length - 2
。
另一种方法是在找到可被27整除的数字后输出:
3,9