[英]Array sum of elements to third array
我希望代碼獲取兩個數組的相應元素的總和。 我試圖添加元素。 但是,我對如何做到這一點感到非常困惑。 我試圖獲得此輸出以匹配測試。 用戶將輸入數組的長度以及數組(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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.