繁体   English   中英

二维数组,方法和变量

[英]two dimensional array, methods and variables

好像我的主要变量nm不能通过方法尺寸更改。 控制台说这行创建方法时存在问题[a] [j] = unos.nextInt(); 但是,如果我更改此行,则为private int [] [] a = new int [n] [m]; 并输入[3] [4]之类的任何数字,该程序均有效,但使用[n] [m]则无效,您能帮助我吗,这段代码有什么问题。 控制台:a [1] [1] =线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:0预先感谢。

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();
    }
}
}

问题是

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

在执行构造函数中的代码之前被执行。 也就是说,在未设置nm执行new操作,此时默认情况下将它们初始化为0。 因此,它正在分配没有行或列的数组。

要解决此问题,请将以上内容更改为

private int[][] a;

并在设置nm之后在构造函数中对其进行初始化:

a = new int[n][m];

有关创建实例时事物执行顺序的更多信息,请参见JLS的本部分

就像@ajb所说的那样,在变量nm使用Scanner获得那里的值之后,初始化数组。 您可以在dimensions()方法中执行此操作。

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.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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