Java的N * N矩阵

时间:2015-03-16 01:57:49

标签: java

这就是我写的:

import javax.swing.JOptionPane;

public class JavaTest{
    public static void main(String[] args){
    String numberString = JOptionPane.showInputDialog(null, "Enter number here: ",
            null, JOptionPane.INFORMATION_MESSAGE);
        int number = Integer.parseInt(numberString);
        printMatrix(number);
    }

public static void printMatrix(int n){
    int[][] myList = new int[n][n];
    String output = "";

    for (int row = 1; row <= n; row++){
        for (int col = 1; col <= n; col++){
            myList[row][col] = (int) (Math.random() * 2);
        }
    }
    for (int row = 1; row <= n; row++){
        for (int col = 1; col <= n; col++){
            if (col == n){
                output += "\n" + myList[row][col];
            }
            else{
                output += myList[row][col] + " ";
            }
        }
    }


    if (n < 0){
        JOptionPane.showMessageDialog(null,
                "Invalid input!");
    }
    else{
        JOptionPane.showMessageDialog(null,
                output);
    }
    }
}

我运行它并在对话框中输入3,eclipse IDE显示

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at JavaTest.printMatrix(JavaTest.java:17)
    at JavaTest.main(JavaTest.java:8)

我想在第17和第8行程序出错但我不知道如何改进它。 我该怎么做才能改进我的代码?谢谢!

1 个答案:

答案 0 :(得分:1)

您从1循环到n:

for (int row = 1; row <= n; row++){
    for (int col = 1; col <= n; col++){

索引从0开始,而不是从1开始。循环应该从0到n-1:

for (int row = 0; row < n; row++){
    for (int col = 0; col < n; col++){

(同样的错误可能在其他地方,而不仅仅是抛出异常的第一行。)