我想打印大小爲(m + 1 X n + 1)的矩陣,其中m & n是用戶輸入的兩個字符串的長度。當我打印矩陣時,爲什麼會出現ArrayIndexOutofBounds異常?矩陣中的ArrayIndexOutOfBoundsException
import java.util.*;
import java.io.File;
public class Strings {
private static int alen ,blen;
int [][] matrix = new int[alen+1][blen+1];
public static void main(String[] args){
Strings String1 = new Strings();
String a,b;
System.out.println("Enter String a: ");
Scanner usrip = new Scanner(System.in);
a = usrip.next();
alen = a.length();
System.out.println("Enter String b: ");
b = usrip.next();
blen = b.length();
usrip.close();
System.out.println("Matrix size: " + alen + "X" + blen);
String1.printMatrix();
/*System.out.println("Execute populate method: ");
String1.populateMatrix();*/
}//end of main
public void printMatrix(){
for(int i=0;i<alen+1;i++)
{
for(int j=0;i<blen+1;j++)
{
System.out.print(matrix[i][j]);
}
}
}//end of printMatrix
採樣運行:
Enter String a:
apple
Enter String b:
java
Matrix size: 5X4
0Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Strings.printMatrix(Strings.java:38)
at Strings.main(Strings.java:25)
謝謝你,當我推矩陣初始化爲主要方法,你說,我的mehtod不承認所謂的矩陣對象,它說「矩陣不能解析爲變量」。 – ZeExplorer