我是Java的初学者,我正在尝试创建一个使用两个数组的程序,并将两个数组中的每个对应数字相乘,然后创建一个显示输出的第三个数组。我尝试并继续遇到错误。
我创建了一个附加方法,该方法接受数组并将它们相乘,但是我不确定是否正确创建了返回乘积的第三个数组。
对于如何解决此问题或进行任何更正的任何帮助或见解,我们深表感谢。感谢您的宝贵时间!
public static void main(String[] args){
int[] setA = {1,2,3,4,5};
int[] setB = {2,4,6,7,8};
arrayProduct(setA, setB);
System.out.print("The product is: " + int[] product);
}
public static int[] arrayProduct(int[] arrayA, int[] arrayB){
int[] product = {};
int i;
for (i = 0; i < arrayA.length; i++) {
int num1 = arrayA[i];
int num2 = arrayB[i];
product += Integer.toString(num1 * num2) + " ";
}
return int[] product;
}
答案 0 :(得分:1)
public static void main(String[] args){
int[] setA = {1,2,3,4,5,6};
int[] setB = {2,4,6,7,8};
//Invoke the arrayProduct method which requires 2 int arrays int[] as parameters. Store the returned int[] in a new int[] called productArray.
int[] productArray = arrayProduct(setA, setB);
//Display the whole array on one line.
System.out.print("The product is: " + Arrays.toString(productArray));
}
//If arrayProduct() is only accessed from within its own class, set the method to private.
private static int[] arrayProduct(int[] arrayA, int[] arrayB){
//You could do some validation here before creating a product[] array to ensure both arrays are of the same length, if arrayA.length = 7 and arrayB.length = 6
//you will get a IndexOutOfBoundsException... when trying to get the product of arrayA[6] * arrayB[6].
int[] product = new int[arrayA.length];
for (int i = 0; i < arrayA.length; i++) {
product[i] = arrayA[i] * arrayB[i];
}
return product;
}
如果您不熟悉Java中的数组,请查看以下链接以获得基本了解https://www.w3schools.com/java/java_arrays.asp