有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

N*N矩阵的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,EclipseIDE显示

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

我猜第17行和第8行的程序出错了,但我不知道如何改进它。 如何改进代码?谢谢


共 (1) 个答案

  1. # 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++){
    

    (除了抛出异常的第一行之外,此错误可能还存在于其他位置。)