gpt4 book ai didi

java - 数组中的两个数字

转载 作者:行者123 更新时间:2023-12-02 02:16:38 24 4
gpt4 key购买 nike

我想要得到两个数字,其乘积等于给定数字。下面是我的代码,但它抛出一个 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];
}
}
}

}

在这种情况下,它应该打印 39,因为这两个数字的乘积等于 27,但事实并非如此工作。有人可以指出原因吗?提前致谢。

最佳答案

您的算法不正确,因为除非其成员位于相邻索引,否则它永远不会找到一对。换句话说,如果您查找 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]

关于java - 数组中的两个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49220500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com