我的程序每运行几次就会给出错误
at outlab6.Battleship.setShips(Battleship.java:75)
at outlab6.Battleship.setBoard(Battleship.java:35)
但我认为我已经设置了代码,以便那些不应该发生。有人可以告诉我我做错了什么以及为什么它不会忽视使这种可能性成为可能的可能性?
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
}
}
}
}
}
答案 0 :(得分:1)
你的问题可能就在这里:
int chosenRow = (int)(Math.random()* rows)+1;
int chosenCol = (int)(Math.random()* cols)+1;
这会在chosenRow
和1
之间提供rows
,在chosenCol
和1
之间提供cols
。当您尝试访问chosenRow == rows
时,spot[chosenRow][chosenCol + i]
将使您脱离数组范围。
您应将其更改为:
int chosenRow = (int)(Math.random()* rows);
int chosenCol = (int)(Math.random()* cols);