Home > Mobile >  Arrays-Java, sum of the elements in same positions with the array
Arrays-Java, sum of the elements in same positions with the array

Time:11-03

I have an exercise and find out what went wrong. I will be grateful for help :)

Write the code that will have two arrays of type int and the return array greater (if one of the two arrays is greater) and the sum of the elements in same positions with the array.

public class TwoArrays {
    public static void main(String[] args) {
        int[] arrayA = {1, 5, 2, 6, 8};
        int[] arrayB = {4, 5, 7, 10, 7, 9, 7};
        int lengthA = arrayA.length;
        int lengthB = arrayB.length;
        int i=0;
        if (lengthA < lengthB) {
            for (arrayB[i] = 0; i < lengthB; i  ) {
                arrayB[i] = arrayA[i]   arrayB[i];
                System.out.println(arrayB[i]);
            }

        } else if (lengthA > lengthB) {
            for (arrayA[i] = 0; i < lengthA; i  ) {
                arrayA[i] = arrayA[i]   arrayB[i];
                System.out.println(arrayA[i]);
            }

        } else {
            for (arrayB[i] = 0; i < lengthB; i  ) {
                arrayB[i] = arrayA[i]   arrayB[i];
                System.out.println(arrayB[i]);
            }
        }
    }
}

CodePudding user response:

It should be

for (int i = 0; i < lengthB; i  )

When you use

for (arrayB[i] = 0; i < lengthB; i  )

You set the first element of your array to 0, not the i index variable like you probably want to.

Also, you should do something like finding which array is larger, then using a variable like bigArray = arrayA, smallArray = arrayB. Then, you only have to write a single for Loop.

CodePudding user response:

Try to check the condition of the first For-Loop again. If you try to access an array at a position, which is larger than the array length you will get a java.lang.ArrayIndexOutOfBoundsException. I suggest you should try to Debug this Code if you have trouble to understand it.

  • Related