Brand new to coding, so sorry if this is a basic question. I'm doing an assignment to program a code for the game battleship in java.
I'm using a method to get the user to input coordinates and then save those coordinates as an array to be used in another method. I understand that a variable within a method does not save.
So I created a return for the method and then created a new variable in my main class and set to the return value of the method.
public static char[][] player1ships() {
System.out.println("PLAYER 1, ENTER YOUR SHIPS' COORDINATES.");
Scanner input = new Scanner(System.in);
char[][] player1 = new char[5][5];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
player1[i][j] = '-';
}
}
for (int i = 1; i <= 5; ) {
System.out.println("Enter location for ship " + i);
int a = input.nextInt();
int b = input.nextInt();
if ((a >= 0 && a < 5) && (b >= 0 && b < 5) && (player1[a][b] == '-')) {
player1[a][b] = '@';
i++;
} else if ((a >= 0 && a < 5) && (a >= 0 && b < 5) && (player1[a][b] == '@'))
System.out.println("You can't place two or more ships on the same location");
else if ((a < 0 || a >= 5) || (b < 0 || b >= 5))
System.out.println("You can't place ships outside the " + 5 + " by " + 5 + " grid");
}
return player1;
}
I want to run the method so the user enters the coordinates and then save the return array to use later. However, When I run the program it seems to run the method twice as the the output prompts the user through 2 cycles of "enter location".
When I added the test line at the end, it does print the correct symbol at the index array so it does seem to save the updated arary.
So how do I save the return as a variable without running and printing the whole method again?
public static void main(String[] args) {
char [][] strike = player1ships();
player1ships();
//test to see if array updated
System.out.println(strike[0][0]);
}
}
This is the result of the program running...and going through the player1ships method twice instead of once.
showing how it prompts user through two cycles before printing out the last line
In main method removing/commenting the second method call and re run the code.It working fine
{
public static void main(String[] args) {
char [][] strike = player1ships();
player1ships(); ----> this line
//test to see if array updated
System.out.println(strike[0][0]);
}
}
Hope its working fine?