John
John

Reputation: 37

How can I sum these two arrays into a new one?

How can I sum these two arrays into a new one? Where the first value of the arrayA sums the first value of the arrayB?

public class Exercises {

    static BufferedReader in = new BufferedReader(
            new InputStreamReader(System.in));
    static PrintStream out = System.out;

    public static void main(String[] args) throws IOException {
        int numbersA[] = new int[5];
        int numbersB[] = new int[5];
        int numbersC[] = new int[5];

        for (int i = 0; i < 5; i++) {
            out.print("Please insert a number for the first array: ");
            numbersA[i] = Integer.parseInt(in.readLine());
        }

        for (int i = 0; i < 5; i++) {
            out.print("Please insert a number for the second array: ");
            numbersB[i] = Integer.parseInt(in.readLine());
        }
        int j = 0;
        for (int i = 0; i < 5; i++) {
            numbersC[j] = (numbersA.length[i] + numbersB.length[i]);
        }
        {

            out.print("The sum of the two arrays are: " + numbersC[j] + " ");
        }
        out.println();
    }
}

Upvotes: 1

Views: 64

Answers (2)

Mohammed Al-Reai
Mohammed Al-Reai

Reputation: 2786

try to delete the numbersC[j] = (numbersA.length[i] + numbersB.length[i]); length from both use this shape numbersC[i] = numbersA[i] + numbersB[i]; i think it will be work now

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201429

You were pretty close. numbersA[i] and numbersB[i] (not the length of each array). Also, you don't need j and should print the prelude before the loop. Like,

out.print("The sum of the two arrays are: ");
for (int i = 0; i < 5; i++) {
    numbersC[i] = numbersA[i] + numbersB[i];
    out.print(numbersC[i] + " ");
}
out.println();

Finally, your code relies on magic numbers (hard coded array lengths). That is bad practice, instead you should use the array.length so your code doesn't require changing when your array sizes change. Like,

int[] numbersA = new int[5];
int[] numbersB = new int[5];
for (int i = 0; i < numbersA.length; i++) {
    out.print("Please insert a number for the first array: ");
    numbersA[i] = Integer.parseInt(in.readLine());
}

for (int i = 0; i < numbersB.length; i++) {
    out.print("Please insert a number for the second array: ");
    numbersB[i] = Integer.parseInt(in.readLine());
}
int[] numbersC = new int[Math.min(numbersA.length, numbersB.length)];
out.print("The sum of the two arrays are: ");
for (int i = 0; i < numbersC.length; i++) {
    numbersC[i] = numbersA[i] + numbersB[i];
    out.print(numbersC[i] + " ");
}
out.println();

Upvotes: 3

Related Questions