【发布时间】:2015-01-28 19:35:19
【问题描述】:
我的程序每运行几次就会给我一个错误
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
}
}
}
}
}
【问题讨论】:
-
我会看看这两行
int chosenRow = (int)(Math.random()* rows)+1和int chosenCol = (int)(Math.random()* cols)+1我还没有运行你的代码,但是 +1 可能会把你搞砸.. -
(int)(Math.random()* rows)+1- 想象rows是1。那么每次你会得到1,数组当然从0开始,所以你总是会得到和索引超出范围。它应该是(int)(Math.random()* rows)。