编译已经成功,运行时出现Exception in thread "main" java.lan

来源:百度知道 编辑:UC知道 时间:2024/05/21 06:59:53
class test
{
public static void main(String [] args)
{
int a[][]=new int[5][5];
int x=0,i,j;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
a[i][j]=x++;
System.out.print(a[i][j]+" ");
System.out.println();
}

}

}

执行
C:\Javawork>java test
后 屏幕出现

0 0 0 0 0
Exception in thread "main" java.lan
at test.main(test.java:12)

classpath=C:\Javawork>java test

请问这是什么原因呢?

首先类名大写:Test
class Test
{
public static void main(String [] args)
{
int a[][]=new int[5][5];
int x=0,i,j;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{ -- 少括号
a[i][j]=x++;
System.out.print(a[i][j]+" ");
System.out.println();
}-- 少括号
}

}

}

由于少括号,所以
System.out.print(a[i][j]+" ");
System.out.println();
是在第一个for循环中执行,
原因,当第二个循环执行完毕后,j=5,for判断j>5,条件不符合,退出循环,执行System.out.print(a[i][j]+" ");这时数组为a[i][5],从而导致数组下标越界,加上括号就行了

下面是我帮你改过之后的程序
经测试运行成功:

class Test {
public static void main(String[] args) {
int a[][] = new int[5][5];
int x = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++){
a[i][j] = x++;
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}

输出结果为:
0 1 2 3 4