gpt4 book ai didi

java - 第三个数组的元素的数组和

转载 作者:行者123 更新时间:2023-11-30 08:10:32 26 4
gpt4 key购买 nike

我希望代码获得两个数组对应元素的总和。我正在尝试添加元素。但是,我真的很困惑如何做到这一点。我试图让这个输出与测试相匹配。用户将输入数组的长度以及每个数组(arrayA)和(arrayB)的元素是什么。最后,我希望我的代码将这两个数组的元素添加到数组 C 中。因此输出应如下所示:

Input the length: 5
Enter a value for first array, position 0: 1
Enter a value for first array, position 1: 6
Enter a value for first array, position 2: 13
Enter a value for first array, position 3: -3
Enter a value for first array, position 4: 8
Enter a value for second array, position 0: 9
Enter a value for second array, position 1: -4
Enter a value for second array, position 2: 1
Enter a value for second array, position 3: 65
Enter a value for second array, position 4: 18
first: 1 6 13 -3 8
second: 9 -4 1 65 18
result: 10 2 14 62 26

到目前为止我已经写了代码,但是它只计算数组长度是否为4。请告诉我如何让程序计算任意长度的两个数组的相应元素之和。

import java.util.*;

class ArrayArithmetic
{
public static void main ( String[] args )
{
Scanner in = new Scanner(System.in);
System.out.print("Input the length: ");
int len = in.nextInt();

int[] arrA = new int[len];
int[] arrB = new int[len];
int[] sum = new int[len];
for (int i = 0; i < len; i++){
System.out.print("Enter a value for first array, position " + i + ": ");
arrA[i] = in.nextInt();
}
for (int i = 0; i < len; i++){
System.out.print("Enter a value for second array, position " + i + ": ");
arrB[i] = in.nextInt();
}

for(int i = 0; i < arrA.length; i++)
{
for(int j = 0; i < arrB.length; i++)
{
sum[i] = arrA[i] + arrB[i];

}

for(int i = 0; i < arrA.length; i++)

}

System.out.println("first: "+Arrays.toString(arrA));
System.out.println("second:"+Arrays.toString(arrB));
System.out.println("result: " + sum[0]+"," + sum[1] + "," + sum[2] + "," + sum[3] );


}
}

最佳答案

替换这一段代码:

 for(int i = 0; i < arrA.length; i++)
{
for(int j = 0; i < arrB.length; i++)
{
sum[i] = arrA[i] + arrB[i];
}

 for(int i = 0; i < len; i++)
{
sum[i] = arrA[i] + arrB[i];
}

最后几行:

for(int i = 0; i < arrA.length; i++)

}

System.out.println("first: "+Arrays.toString(arrA));
System.out.println("second:"+Arrays.toString(arrB));
System.out.println("result: " + sum[0]+"," + sum[1] + "," + sum[2] + "," + sum[3] );

System.out.println("first: "+Arrays.toString(arrA));          
System.out.println("second:"+Arrays.toString(arrB));
System.out.println("result: " + Arrays.toString(sum));

关于java - 第三个数组的元素的数组和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30448928/

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