[英]N * N matrix by 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循環到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++){
(除了引發異常的第一行以外,此錯誤也可能發生在其他地方。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.