【发布时间】:2016-12-18 13:48:08
【问题描述】:
似乎我的主要变量 n 和 m 无法通过方法维度进行更改。控制台说 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 间距标准(不是我喜欢的所有标准,但我接受它们),我认为最好在有大量读者的网站上工作.