Turning 2 arrays into a two-dimensional array in java

Hi, I am trying to take two arrays and turn them into one 2-dimensional array. However, I get an error all the time:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
 at test5.sum(test5.java:12)
 at test5.main(test5.java:38)

Here is my code:

public class test5 {
    int[][] final23;

    public int[][] sum(int[] x, int[] y) {
        final23 = new int[2][x.length];
        for (int i = 0; i < final23[i].length; i++) {

            final23[1][i] = x[i];
            final23[2][i] = y[i];
        }
        return final23;
    }

    public void print() {
        for (int i = 0; i < final23[i].length; i++) {
            for (int j = 0; j < final23[i].length; j++) {

                System.out.print(final23[i][j] + " ");
            }
        }
    }

    public static void main(String[] args) {
        int l[] = { 7, 7, 3 };
        int k[] = { 4, 6, 2 };
        test5 X = new test5();

        X.sum(k, l);
        X.print();
    }
}

I am not sure what the problem is. Sorry if the question is dumb, I'm new to coding!

+3
source share
3 answers

Your program also has a second problem. You have this loop in both methods sumand print:

for (int i = 0; i < final23[i].length; i++)

In the sum method, this should be

for (int i = 0; i < final23[0].length; i++)

And in the printing method

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

Otherwise, you will receive again ArrayIndexOutOfBoundsException.

, , . , .

+3

:

final23 [2][i] = y[i];

Java 0. , final23 [0] [1].

n 0 n-1.

+5

Try

for (int i = 0; i < final23[i].length; i++)
 {

  final23 [0][i] = x[i];
  final23 [1][i] = y[i];
 }

Remember that all arrays are 0-based, even n-dimensional.

+1
source

Source: https://habr.com/ru/post/1764244/


All Articles