简体   繁体   中英

Java program stuck in user input loop

I'm creating a small 'game' program where a player enters a floor/room number, but when the player guess it gets stuck and loops on a single player and doesn't move to the next player and doesn't tell if the player is correct or incorrect as a guess where the dog is being held in the building.

PuppyPlay.java:

import java.util.Random;
import java.util.Scanner;

/**
 * This program is used as a driver program to play the game from the
 * class LostPuppy.
 *
 * 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.
 *
 */

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"));
  }
}

LostPuppy.java:

import java.util.Random; // Randomize the dog placement in building
import java.util.Scanner; // User input

/**
 * This program is used as a program to play the game from the
 * driver PuppyPlay.java
 *
 * 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.
 *
 */

 public class LostPuppy{

   private char[][] myHidingPlaces; // Defining class fields for assignment
   private int myFloorLocation;
   private int myRoomLocation;
   private char myWinner;
   private boolean myFound;

   /**
   * Creates constructor takes floor/room numbers inputted by user
   *
   * @param theFloors for number of floors
   * @param theRooms for number of rooms
   */

   public LostPuppy(int theFloors, int theRooms) {
      Random random = new Random();
      myHidingPlaces = new char[theFloors][theRooms];

      // Filling array with spaces
      int i;
      for (i = 0; i < theFloors; i++) {
         for (int k = 0; k < theRooms; k++) {
            myHidingPlaces[i][k] = ' ';
         }   
      }

      myFloorLocation = random.nextInt(theFloors);
      myRoomLocation = random.nextInt(theRooms);
      myHidingPlaces[myFloorLocation][myRoomLocation] = 'P';
      myWinner = ' ';
      myFound = false;
   }

   /**
   * Checks if room has been searched prior
   *
   * @param theFloors for number of floors
   * @param theRooms for number of rooms
   */

   public boolean roomSearchedAlready(int theFloors, int theRooms) {
      boolean searchedRoom;
      if (myHidingPlaces[theFloors][theRooms] == ' ') {
         myHidingPlaces[theFloors][theRooms] = 'S';
         searchedRoom = false;
      } else {
         searchedRoom = true;
      }  
      return searchedRoom;
      }

   /**
   * Checks if the puppy has been found
   *
   * @param theFloors for number of floors
   * @param theRooms for number of rooms
   */

   public boolean puppyLocation(int theFloors, int theRooms) {
      if (myHidingPlaces[myFloorLocation][myRoomLocation] == myHidingPlaces[theFloors][theRooms]) {
         myFound = true;
      } else {
         myFound = false;
      }      
      return myFound;
      }

   /**
   * Checks if floors and rooms won't throw out of bounds error
   *
   * @param theFloors for number of floors
   * @param theRooms for number of rooms
   */

   public boolean indicesOK(int theFloors, int theRooms) {
      boolean indicesFit;
      if (theFloors < numberOfFloors() && theRooms < numberOfRooms()) {
         indicesFit = true;
      } else {
         indicesFit = false;
      }
      return indicesFit;
      }

   /*
   * Checks # of floors and returns it
   */

   public int numberOfFloors() {
      return myHidingPlaces.length;
      }

   /*
   * Checks # of rooms and returns it
   */

   public int numberOfRooms() {
      return myHidingPlaces[0].length;
      }

   /**
   * Checks which player found the dog and won, or if not checks to see what player
   * guessed wrong and puts their # in the box
   *
   * @param theFloors for number of floors
   * @param theRooms for number of rooms
   * @param thePlayer for 1st or 2nd player
   */

   public boolean searchRoom(int theFloors, int theRooms, char thePlayer) {
      if (myHidingPlaces[myFloorLocation][myRoomLocation] == myHidingPlaces[theFloors][theRooms]) {
         myFound = true;
         myWinner = thePlayer;
      } else {
         myHidingPlaces[theFloors][theRooms] = thePlayer;
         myFound = false;
      }      
      return myFound;
      }

   /*
   * toString displays the current hidingPlaces array and it’s contents EXCEPT 
   * the location of the puppy which remains hidden until he/she is found at 
   * which point toString will be called (by the driver) and both the player 
   * who found the puppy and a ‘P’ will be displayed in the same cell….
   *
   *
   *
   */

   public String toString() {
      return null;
      }
 }

To run this code you'll need to put both codes with their respective posted names and run PuppyPlay.java with LostPuppy.java in the same folder FYI.

The problem lied in this place in PuppyPlay :

    found = game.searchRoom(floor, room, players[playerIndex]);
    playerIndex = (playerIndex + 1) % 2;
    System.out.println("\n[" + floor + "], [" + room + "]");
    System.out.println(game.toString());
    s.nextLine();

So your program expect you to input something here, and it will keep waiting until you press enter, so you can just remove that line: s.nextLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM