A B C D E
1 - - - - -
2 - - - - -
3 - - - - -
4 - - - - -
5 - - - - -
I then have to randomly assign a 2x2 enemy ship without displaying it on the board (right now I'm using a second array to hold the location, unless there is an easier way). The user then fires a shot by specifying the row (1-5) & column (A-E) values. If the shot hits the enemy ship, then a '*' is displayed in that location. If it doesn't hit, then an 'x' is displayed in that location. What I'm having trouble with is:
1. I'm not sure if I'm correctly randomly assigning the enemy ship correctly.
2. The user is supposed to enter the column letter, but I don't know how to convert that from int.
3. I'm confused in how to compare the user's input with the array of the enemy ship to see if it was a hit or not.
Here is my code thus far:
import java.util.Scanner;
public class assignment17 {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
System.out.println(" A B C D E");
System.out.println(" 1 - - - - -");
System.out.println(" 2 - - - - -");
System.out.println(" 3 - - - - -");
System.out.println(" 4 - - - - -");
System.out.println(" 5 - - - - -");
final int ROWS = 6;
final int COLS = 6;
char [] [] values = { {' ', 'A', 'B', 'C', 'D', 'E'},
{'1', '-', '-', '-', '-', '-'},
{'2','-', '-', '-', '-', '-'},
{'3','-', '-', '-', '-', '-'},
{'4','-', '-', '-', '-', '-'},
{'5','-', '-', '-', '-', '-'}};
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
System.out.print(" " + values[row][col]);
}
System.out.println("\n");
}
final int shipROW = 2;
final int shipCOL = 2;
int [] [] shipValues = new int [(int)Math.random() * values.length][(int)Math.random() * values[0].length];
System.out.println("Enter a Row Number: ");
int guessRow = in.nextInt();
System.out.println("Enter a Column Letter: ");
int guessColumn = in.nextInt();
//I am having problem with this if statement
if ([guessRow][guessColumn] = shipValues){
values [guessRow][guessColumn] = '*';
System.out.println("hit");
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
System.out.print(" " + values[row][col]);
}
System.out.println("\n");
}
}else{
values [guessRow][guessColumn] = 'x';
System.out.println("miss");
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
System.out.print(" " + values[row][col]);
}
System.out.println("\n");
}
}
}
}

New Topic/Question
Reply




MultiQuote







|