日期:2014-05-20  浏览次数:20840 次

【Java基准求教-数组】数组越界异常,但我看不出越界
大家好,我写了下面一段程序,但是提示数组越界:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15
at initial.count(Java6_6_7.java:14)
at initial.Check(Java6_6_7.java:19)
at Java6_6_7.main(Java6_6_7.java:47)
但是我看不出来越界,请大家帮忙看看。原程序如下:
出错的地方用红字标出来了。都是和count这个方法有关系。
import java.util.*;

class initial{
int[][] map=new int[15][];
public void start(){
for(int i=0;i<map.length;i++)
map[i]=new int[15];
for(int i=0;i<map.length;i++)
for(int j=0;j<map[i].length;j++)
map[i][j]=0;
}
int count(Point p,int dx,int dy,int col){
int i=0;
while(map[p.x+(i+1)*dx][p.y+(i+1)*dy]==col)
{i++;}
return i;
}
boolean Check(Point p,int col){
if(count(p,1,0,col)+count(p,-1,0,col)==4)
return true;
if(count(p,0,1,col)+count(p,0,-1,col)==4)
return true;
if(count(p,1,1,col)+count(p,-1,-1,col)==4)
return true;
if(count(p,-1,1,col)+count(p,1,-1,col)==4)
return true;
return false;
}
}

class Point{
int x;
int y;
}

public class Java6_6_7 {
public static void main(String[] args) {
System.out.println("棋盘初始化...");
initial board=new initial();
board.start();
System.out.println("棋盘初始化完成。");
Point p=new Point();
p.x=1;
p.y=1;
int col=0;
int i=0;
while(board.Check(p, col)){
if(i%2==0){
System.out.println("请输入白棋的坐标:");
Scanner white_x=new Scanner(System.in);
Scanner white_y=new Scanner(System.in);
p.x=white_x.nextInt();
p.y=white_y.nextInt();
col=1;
board.Check(p, col);
i++;
}else{
System.out.println("请输入黑棋的坐标:");
Scanner black_x=new Scanner(System.in);
Scanner black_y=new Scanner(System.in);
p.x=black_x.nextInt();
p.y=black_y.nextInt();
col=-1;
board.Check(p, col);
i++;
}
}
String color=new String();
if(col==-1)
color="黑色";
else
color="白色";
System.out.println(color+"胜!");
}
}

------解决方案--------------------
你刚开始map里面都是0,都等于col
while (map[p.x + (i + 1) * dx][p.y + (i + 1) * dy] == col) {
i++;
}
这里i就会一直++,直到i=14,数组就越界了。
自己加个断点调试就知道了。