Question: Given the print method below which is used to print the ocean with row labels A to J and column labels 0 to 9, at
Given the print method below which is used to print the ocean with row labels A to J and column labels 0 to 9, at the moment the only way to input coordinates is by entering an integer for the row, followed by a space, followed by another integer for the column. Looking at the additional methods, how can this be changed so I can input a String (from A to J) for rows instead of an integer?
public void print() { String space = " "; int rows; int columns; char rowLabel = 'A'; for (rows = -1; rows <= 9; rows++) { for (columns = -1; columns <= 9; columns++) { if (rows == -1) { if (columns > -1) { space += " " + columns; } } else if (columns == -1) { space += rowLabel + " "; rowLabel++; } else if (!this.checkIfShipIsHit(rows, columns)) { space += "~" + " "; } else { space += shipLocationArray[rows][columns].toString() + " "; } } space += " "; } // Print the ocean. System.out.println(space); } public void play(){ print(101); print(1); ocean.placeAllShipsRandomly(); boolean isGameOver = ocean.isGameOver(); sc = new Scanner(System.in); //print the ocean and start the game ocean.print(); print(3); while (!isGameOver){ print(2); String input = sc.nextLine(); //check if input is valid while (!checkValidInput(input)){ print(99); input = sc.nextLine(); } //get coordinates and fire int[] coordinates = getCoordinates(input); int row = coordinates[0]; int column = coordinates[1]; ocean.shootAt(row, column); availableSpot[row][column] = false; isGameOver = ocean.isGameOver(); ocean.print(); print(3); print(100); } //print info saying you win print(4); } public int[] getCoordinates(String input){ int[] coordinates = new int[2]; String[] strList = input.split(" "); int row = Integer.parseInt(strList[0]); int column = Integer.parseInt(strList[1]); coordinates[0] = row; coordinates[1] = column; return coordinates; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
