gpt4 book ai didi

java - Java 的 N * N 矩阵

转载 作者:行者123 更新时间:2023-12-01 11:47:03 25 4
gpt4 key购买 nike

这是我写的:

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 循环到 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++){

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

关于java - Java 的 N * N 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29068538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com