我正在为游戏 Battleship 编写 placeShips 方法。它在大多数情况下都有效......除非我试图放置一艘船,并且它遇到错误情况(下船,该位置的另一艘船等)它会在空间直到它意识到它不应该。我尝试使用级联 if 语句,但我不确定如何解决这个问题。这是代码片段。有五艘不同的船,但这是仅将第一个放置在 10x10 数组中的代码,所有字符都初始化为 ~。
int count=1;
while(count<=5){
start: {
if(count==1){
System.out.println("What row and column would you like to place your aircraft carrier?");
System.out.println("Row?");
int row1 = IO.readInt();
if(row1>9 || row1<0){
IO.reportBadInput();
break start;
}
System.out.println("Column?");
int column1 = IO.readInt();
if(column1>9 || column1<0){
IO.reportBadInput();
break start;
}
System.out.println("How would you like to orient your aircraft carrier? 1. Down, 2. Up, 3. Left, 4. Right");
int orientation = IO.readInt();
if(orientation==1){ //oriented down
for(int z=0; z<5; z++){ //places the aircraft carrier, DOWN
if((row1+z)>=board.length){
System.out.println("This will go off the board. You can't place your ship here! Try again.");
IO.reportBadInput();
break start;
}
else if(board[row1+z][column1]!='~'){
System.out.println("Oops! You can't place your ship there. Ship already in this location. Try again.");
IO.reportBadInput();
break start;
} //checks if there's anything else already in that space
else{
board[row1 + z][column1]= 'A';
}
}
}
if(orientation==2){ //oriented up
for(int z=0; z<5; z++){ //places the aircraft carrier, UP ORIENTATION
if((row1-z)<0){
System.out.println("This will go off the board. You can't place your ship here! Try again.");
IO.reportBadInput();
break start;
}
else if(board[row1-z][column1]!='~'){
System.out.println("Oops! You can't place your ship there. Ship already in this location. Try again.");
IO.reportBadInput();
break start;
} //checks if there's anything else already in that space
else{
board[row1 - z][column1]= 'A';
}
}
}
if(orientation==3){
for(int z=0; z<5; z++){ //places the aircraft carrier, LEFT ORIENTATION
if((column1-z)<0){
System.out.println("This will go off the board. You can't place your ship here! Try again.");
IO.reportBadInput();
break start;
}
else if(board[row1][column1-z]!='~'){
System.out.println("Oops! You can't place your ship there. Ship already in this location. Try again.");
IO.reportBadInput();
break start;
} //checks if there's anything else already in that space
else{
board[row1][column1-z]= 'A';
}
}
}
if(orientation==4){
for(int z=0; z<5; z++){ //places the aircraft carrier, RIGHT ORIENTATION
if((column1+z)>=9){
System.out.println("This will go off the board. You can't place your ship here! Try again.");
IO.reportBadInput();
break start;
}
else if(board[row1][column1+z]!='~'){
System.out.println("Oops! You can't place your ship there. Ship already in this location. Try again.");
IO.reportBadInput();
break start;
} //checks if there's anything else already in that space
else{
board[row1][column1+z]= 'A';
}
}
}
count++;
}