Answered step by step
Verified Expert Solution
Question
1 Approved Answer
In a game of Battleship, I'd like to receive input from the user as follows: a string (A to J) for the row, followed by
In a game of Battleship, I'd like to receive input from the user as follows: a string (A to J) for the row, followed by an integer from 0 to 9 for the column. At the moment input is only allowed by entering an integer for both row and column selection. How can this be changed to receive a string input for row while keeping column input as integers? I attempted to change the row data type from int to String (String.valueOf(coordinates[0]0)), but couldn't get it to work. It still only accepted integer input for row selection. Any help is much appreciated. // check for valid input public boolean checkValidInput(String input){ ArrayListnumList = new ArrayList (); for (int i=0;i<10;i++){ numList.add(""+i); } String[] coordinates = input.split(" "); //returns false if there are not 2 strings if (coordinates.length!=2){ return false; } //returns false if any of the strings is not a single digit number for (String str: coordinates){ if (numList.contains(str)==false){ return false; } } //returns false if the coordinates have already been shot at int row = Integer.parseInt(coordinates[0]); int column = Integer.parseInt(coordinates[1]); if (this.availableSpot[row][column]==false){ return false; } return true; } 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; } 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(); } //receive 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); }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started