Java - 2D Array of Manipulation in a Complex Program

Before I ask my question, I want to make some things clear. Firstly, I am new to Java and programming in general. Secondly, this is my second post, so please calm down if I did something wrong. Finally, I would like to explain why what I did was wrong, and not just a plug-in solution in any answers to this post. To better understand the problem, I will write the destination information, then the specified driver class, and then the code of the class that the driver class refers to.

My question is:

How can I get the bottom left of my β€œbuilding” in [0] [0] on my 2D array? Here is an example for loop that works when changing the bottom left corner of a 2D array to [0] [0], but I tried to implement this in my searchRoom method (where the player index is set to myHidingPlaces) and I cannot get myHidingPlaces [0 ] [0] in the lower left corner of my 2D array. I believe that I need to somehow modify the toString method using loops, but I cannot figure out how to do this.

The following is the purpose:

You must create the class "LostPuppy.java", which represents a puppy lost in a multi-story building that contains the same number of rooms on each floor. When creating (or creating) an object of this class, each room on each floor will be initialized as empty (in fact, you will use the space character for this), and a random room will be selected where the puppy is lost. For this purpose, the character β€œP” will be placed at this random location. More detailed information about the constructor is given below.

An object of this class is used as a game for two players to alternately look for a puppy, one room in, until an unfortunate little fang is found. This object will be instantiated and searched by the "program" that was provided to you, allowing you to focus only on the development of the class (the driver program is in the file "PuppyPlay.java")

Fields (of course, all fields are private):

  • An array (char) named myHidingPlaces. This is a building where rows of floors and columns are rooms on each floor (this building has an unusual numbering system, floors and rooms start from scratch).

  • The two integers that will hold the floor and the room where the puppy is lost are called myFloorLocation and myRoomLocation.

  • A char named myWinner, which will be assigned the player character when the player finds a puppy (the driver program uses the numbers "1" and "2" to more clearly distinguish players from the puppy).

  • The logical name myFound, which is set to true when the puppy is found.

Constructor:

  • Gets two integer parameters, as users enter the number of floors and rooms of the building in which the puppy is lost.

  • The constructor creates a 2D array "myHidingPlaces" as an array of characters with the first parameter for the rows (theFloors) and the second parameter as columns (theRooms).

  • Initialize myHidingPlaces cells, each of which contains a space '' (executed with single quotes)

  • Set myFloorLocation (puppy is enabled), in random order, using the first parameter
  • Set myRoomLocation (Puppy) at random using the second parameter
  • Set myHidingPlaces [myFloorLocation] [myRoomLocation] to char 'P
  • Install myWinner in one space
  • Set myFound to false

Methods:

  • roomSearchedAlready gets the floor and room to look for and returns true if the room has already been found, false otherwise.

  • puppyLocation gets the floor and room for the search and returns true if the floor and number where the puppy is lost, otherwise false. This method should NOT modify any of the fields.

  • indexOK gets the floor and room to search for and returns true if the floor and room are within the range of array indices, false otherwise (used to verify that these indices will not cause an error when applied to the array).

  • numberOfFloors returns the number of floors in the building (the first floor starts from zero).

  • numberOfRooms returns the number of rooms on each floor of the building (the first room starts at zero and all floors have the same number of rooms).

  • searchRoom gets the gender and number to search, as well as the current player (as a char), and returns true if the puppy is found, otherwise false. If the puppy is NOT found, searchRoom also sets the myHidingPlaces array on the received floor and the location of the room to the value of the accepted player (a '1 or' 2) OR, when it is found, sets the myWinner field to the current player AND sets myFound to true.

  • toString displays the current hidingPlaces array and its contents EXCLUDES the location of the puppy that remains hidden until it is found, at which point toString (driver) will be called, and both the player who found the puppy and "P" will be displayed in one cell ....

  • NOW and possibly the inconvenient part of the toString output. As a rule, when displaying a 2D array, cell [0] [0] is displayed in the upper left corner, as is the case with matrices. However, since the puppy decided to get lost in the building, and not in the matrix, it would make it more visual to have the first floor (line 0) displayed below, the second floor above it ... and, finally, the upper floor, well ... above! to save the words, carefully look at the run example presented on the next page. Your result should look the same as on the next page in the sample run.

Here is the driver program:

import java.util.Random; import java.util.Scanner; /** * This program is used as a driver program to play the game from the * class LostPuppy. Not to be used for grading! * * A puppy is lost in a multi-floor building represented in the class * LostPuppy.class. Two players will take turns searching the building * by selecting a floor and a room where the puppy might be. * * @author David Schuessler * @version Spring 2015 */ public class PuppyPlay { /** * Driver program to play LostPuppy. * * @param theArgs may contain file names in an array of type String */ public static void main(String[] theArgs) { Scanner s = new Scanner(System.in); LostPuppy game; int totalFloors; int totalRooms; int floor; int room; char[] players = {'1', '2'}; int playerIndex; boolean found = false; Random rand = new Random(); do { System.out.print("To find the puppy, we need to know:\n" + "\tHow many floors are in the building\n" + "\tHow many rooms are on the floors\n\n" + " Please enter the number of floors: "); totalFloors = s.nextInt(); System.out.print("Please enter the number of rooms on the floors: "); totalRooms = s.nextInt(); s.nextLine(); // Consume previous newline character // Start the game: Create a LostPuppy object: game = new LostPuppy(totalFloors, totalRooms); // Pick starting player playerIndex = rand.nextInt(2); System.out.println("\nFloor and room numbers start at zero '0'"); do { do { System.out.println("\nPlayer " + players[playerIndex] + ", enter floor and room to search separated by a space: "); floor = s.nextInt(); room = s.nextInt(); //for testing, use random generation of floor and room //floor = rand.nextInt(totalFloors); //room = rand.nextInt(totalRooms); } while (!game.indicesOK(floor, room) || game.roomSearchedAlready(floor, room)); found = game.searchRoom(floor, room, players[playerIndex]); playerIndex = (playerIndex + 1) % 2; System.out.println("\n[" + floor + "], [" + room + "]"); System.out.println(game.toString()); s.nextLine(); } while (!found); playerIndex = (playerIndex + 1) % 2; System.out.println("Great job player " + players[playerIndex] +"!"); System.out.println("Would you like to find another puppy [Y/N]? "); } while (s.nextLine().equalsIgnoreCase("Y")); } } 

Finally, here is my test code:

 import java.util.Random; import java.util.Scanner; public class LostPuppy { int value; char[][] myHidingPlaces; int myFloorLocation; int myRoomLocation; char myWinner; boolean myFound; Random random = new Random(); public LostPuppy(int theFloors, int theRooms) { myHidingPlaces = new char[theFloors][theRooms]; for (int i = theFloors - 1; i >= 0; i--) { for (int j = 0; j <= theRooms - 1; j++) { myHidingPlaces[i][j] = ' '; } } myFloorLocation = random.nextInt(theFloors); myRoomLocation = random.nextInt(theRooms); myHidingPlaces[myFloorLocation][myRoomLocation] = 'P'; myWinner = ' '; myFound = false; } public boolean roomSearchedAlready(int floor, int room) { return (myHidingPlaces[floor][room] == '1' || myHidingPlaces[floor][room] == '2'); } public boolean puppyLocation(int floor, int room) { return (myHidingPlaces[floor][room] == 'P'); } public boolean indicesOK(int floor, int room) { return (floor <= myHidingPlaces.length && room <= myHidingPlaces[0].length); } public int numberOfFloors() { return myHidingPlaces.length - 1; } public int numberOfRooms() { return myHidingPlaces[0].length - 1; } public boolean searchRoom(int floor, int room, char player) { if (puppyLocation(floor, room)) { myFound = true; myWinner = player; return true; } else { myHidingPlaces[floor][room] = player; return false; } } public String toString() { int rooms = myHidingPlaces[0].length; int floors = myHidingPlaces.length; System.out.print(" "); for (int x = 0; x < rooms; x++) { System.out.print("___"); } for (int y = 0; y < rooms - 1; y++) { System.out.print("_"); } System.out.print("\n"); for (int r = 0; r < floors; r++) { System.out.print("| "); for (int c = 0; c < rooms; c++) { if (myHidingPlaces[r][c] == 'P' && myFound) { System.out.print("" + myWinner + "" + myHidingPlaces[r][c] + "| "); } else if (myHidingPlaces[r][c] == 'P' && !myFound) { System.out.print(" | "); } else { System.out.print(myHidingPlaces[r][c] + " | "); } //System.out.print(myHidingPlaces[r][c] + " | "); } System.out.print("\n"); for (int i = 0; i < rooms; i++) { System.out.print("|___"); } System.out.print("|\n"); } return ""; } } 
+6
source share
1 answer

It is not possible to create a reverse array in Java, but you do not need it. You need to think about the building and work with it the same way you do with matrices. However, you need to print it in reverse order. Also, there is no change in position in the array by the link you provided, it is just a traversal of the array from the last index to the first.

So, you need to print the array in reverse order, and that is pretty easy. You need to change one line in the toString method, change

 for (int r = 0; r < floors; r++) 

to

 for (int r = floors - 1; r >= 0; r--) 

And you will get the right result!

Also in this case you do not need to fill the array from the last to the first (at least because you are filling it with the same value) as you do

 for (int i = theFloors - 1; i >= 0; i--) { for (int j = 0; j <= theRooms - 1; j++) { ... } } 

Better if you do it like this (just read your code)

 for (int i = 0; i < theFloors; i++) { for (int j = 0; j < theRooms; j++) { ... } } 

As @Dante said, you also need to fix the indicesOK method, because the last index of the array is its length - 1 , so when you access the myHidingPlaces.length or myHidingPlaces[i].length will be thrown.

 public boolean indicesOK(int floor, int room) { return (floor < myHidingPlaces.length && room < myHidingPlaces[0].length); } 
+2
source

All Articles