简体   繁体   中英

two dimensional array, methods and variables

Seems like my main variables n and m cant be changed via method dimensions. Console says that there is a problem at method create in this line a [ i ][ j ] = unos.nextInt(); but if i change this line private int[ ][ ] a = new int[n][m]; and put any number like [3][4], the program works, but with [n][m] it does not, can u help me guys, whats wrong with this code. CONSOLE: a[1][1]=Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 Thanks in advance..

import java.util.Scanner;

public class Matrica {
private int n, m;
private Scanner unos = new Scanner(System.in);

public void dimensions() {
    System.out.print("n: ");
    n = unos.nextInt();
    System.out.print("m: ");
    m = unos.nextInt();

}

private int[][] a = new int[n][m]; // if i put [2][2] or any other number, instead [n][n], program works

public void create() {
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++) {
            System.out.print("a[" + (i + 1) + "][" + (j + 1) + "]=");
            a[i][j] = unos.nextInt(); // console points that this is the problem
        }
}

public void print() {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            System.out.printf("%d\t", a[i][j]);
        }
        System.out.println();
    }
}
}

The problem is that

private int[][] a = new int[n][m]; 

is being executed before the code in the constructor is executed. That is, the new is being done when n and m haven't been set, and at this point they've been initialized to 0 by default. So it's allocating an array with no rows or columns.

To fix this, change the above to

private int[][] a;

and initialize it in the constructor, after n and m have been set:

a = new int[n][m];

For more information on the order in which things are executed when an instance is created, see this section of the JLS .

Like @ajb said, initialize the array after the variables n & m have obtained there values using the Scanner . You can do this in the dimensions() method.

public void dimensions() {
    System.out.print("n: ");
    n = unos.nextInt();
    System.out.print("m: ");
    m = unos.nextInt();
    a = new int[n][m]; //Add the following line.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM