[英]Array index out of bounds exception java while using loops
Every few runs of my program it gives me the error 我的程序每运行几次,就会给我错误
at outlab6.Battleship.setShips(Battleship.java:75)
at outlab6.Battleship.setBoard(Battleship.java:35)
But I thought that I was already setting the code up so that those shouldn't happen. 但是我以为我已经在设置代码了,这样就不会发生了。 Can someone tell me what I did wrong and why it's not ignoring the possibilities that make that possible? 有人可以告诉我我做错了什么,为什么它不忽略使之成为可能的可能性?
package outlab6;
import java.util.Scanner;
public class Battleship {
private int rows;
private int cols;
private Spot spot[][];
Scanner input = new Scanner(System.in);
public Battleship(int rows, int cols){
this.rows = rows;
this.cols = cols;
}
public void setBoard(){
spot = new Spot[rows][cols];
for(int i = 0; i < rows; i++){
for( int j = 0; j < cols; j++){
spot[i][j] = new Spot();
}
}
//setup board to be completely empty
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
spot[i][j].setShip(0);
}
}
// //test code
// for(int i = 0; i < rows; i++){
// for(int j = 0; j < cols; j++){
// System.out.print(spot[i][j].getShip());
// }
// System.out.println();
// }
setShips();
}
public void printBoard(boolean active){
}
public boolean over() {
return false;
}
public void makeGuess() {
input.nextInt();
}
public void printStatistics() {
}
public void setShips(){
//this method creates and places the ships
//start with carrier and move on down
for(int i = 5; i > 1; i--){
int col;
int row;
boolean valid = false;
//set a direction
int direction = (int)(Math.random()*2)+1;
//System.out.println(direction);
//get a valid spot
while(!valid){
//generate a location
int chosenRow = (int)(Math.random()* rows)+1;
int chosenCol = (int)(Math.random()* cols)+1;
System.out.println("Row:" + chosenRow);
System.out.println("Col:" + chosenCol);
//check to see if spot is open
//for horizontal ships
if(chosenCol + i < cols){
for(int j = 0; j < i; j++){
if(spot[chosenRow][chosenCol + i].getShip() == 0){
valid = true;
}else{
valid = false;
}
}
}else{
//go through again
}
}
}
}
}
Your problem is probably here : 您的问题可能在这里:
int chosenRow = (int)(Math.random()* rows)+1;
int chosenCol = (int)(Math.random()* cols)+1;
This will give you a chosenRow
between 1
and rows
, and a chosenCol
between 1
and cols
. 这会给你一个chosenRow
之间1
和rows
和chosenCol
之间1
和cols
。 Having chosenRow == rows
will bring you out of the array bounds when you try to access spot[chosenRow][chosenCol + i]
. 选择了chosenRow == rows
后,当您尝试访问spot[chosenRow][chosenCol + i]
时,将带您离开数组范围。
You should change it to : 您应该将其更改为:
int chosenRow = (int)(Math.random()* rows);
int chosenCol = (int)(Math.random()* cols);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.