【问题标题】:Product of two arrays两个数组的乘积
【发布时间】:2020-05-04 06:56:52
【问题描述】:

我是 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;

} 

【问题讨论】:

  • product = arrayProduct(setA, setB) 可能会让您更接近解决方案(而不是丢弃结果)
  • 您将 product 定义为一个 int 数组,但您正试图将字符串连接到它。目前尚不清楚您希望输出是字符串、产品数组还是单个 int(产品的总和)。
  • @eran 我需要它是一个产品数组,例如 setA(1,2) setB(3,4) product(3,8) 但我知道我做错了什么跨度>

标签: java product multiplication


【解决方案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

【讨论】:

  • 我一直在 Arrays.toString(productArray)) 中收到错误“找不到符号”我了解您正在将数组类型转换为字符串以便它可以打印,但我一直收到错误.感谢您的帮助,不管@bradley
  • 导入 java.util.Arrays;进入你的java类。
猜你喜欢
  • 1970-01-01
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多