【问题标题】:two dimensional array, methods and variables二维数组、方法和变量
【发布时间】:2016-12-18 13:48:08
【问题描述】:

似乎我的主要变量 nm 无法通过方法维度进行更改。控制台说 a [ i ][ j ] = unos.nextInt(); 行中的方法 create 存在问题,但是 如果我更改这一行 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();
    }
}
}

【问题讨论】:

  • @Thrasher 你为什么编辑这个来添加所有不需要的空间?这不是典型的 Java 风格,只是看起来很奇怪。
  • @Thrasher 我不建议将来这样做。你的个人风格是你的事,但有一些相当完善的 Java 间距标准(不是我喜欢的所有标准,但我接受它们),我认为最好在有大量读者的网站上工作.

标签: java arrays


【解决方案1】:

问题是

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

在执行构造函数中的代码之前执行。也就是说,new 是在 nm 尚未设置时完成的,此时它们已默认初始化为 0。所以它分配了一个没有行或列的数组。

要解决这个问题,请将上面的内容更改为

private int[][] a;

在构造函数中初始化它,在nm被设置之后:

a = new int[n][m];

有关创建实例时事物执行顺序的更多信息,请参阅this section of the JLS

【讨论】:

    【解决方案2】:

    就像@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.
    }
    

    【讨论】:

    • 嗯,我以为都是订单,不知道那种优先级..学到了一些新东西
    • 这并不总是与您编写代码的顺序有关。 Java 是一种完全面向对象的语言,当您运行代码时,无论您在何处创建类级变量(无论它们是类中的前几行代码还是最后一行),变量都将在实际代码之前创建执行发生。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 2013-08-28
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 2017-03-18
    相关资源
    最近更新 更多