简体   繁体   中英

Loops? I need to figure out how to fix this.

When i run my program and try to add a input. It keeps saying invalid input. Enter again. I know why it did that b/ci added a while loop but that was for inputs less than 1. How can I fix this? I need to display the occupancy rate and the amount of vacant rooms. I am a beginner so I think I have made a stupid mistake. Can somebody help me?

import java.util.Scanner;

public class hotelOccupancy
{
   public static void main(String[] args)
   {
      Scanner input = new Scanner(System.in);

      int floors, numFloors, rooms,totalRoomsOccupied,roomsOccupied, vacant;
      double totalRooms;


      System.out.println("Enter number of floors");
      floors = input.nextInt();

      while(floors < 1);
      {
         System.out.println("Invalid input. Enter again");
      }
      floors = input.nextInt(); 

     numFloors = input.nextInt();
     for(floors = 1; floors <= numFloors; floors++)

     {
         System.out.println("Enter number of rooms in floor");
         rooms = input.nextInt();

         while(rooms < 1);
         {
            System.out.println("Invalid entry. Enter again");
         }

         System.out.println("Enter number of rooms occupied for floor" + floors);
         roomsOccupied = input.nextInt();

         totalRoomsOccupied = input.nextInt();
         totalRoomsOccupied = totalRoomsOccupied + roomsOccupied;

     }

     rooms = input.nextInt();
     totalRoomsOccupied = input.nextInt();


     vacant = rooms - totalRoomsOccupied;

     totalRooms = input.nextDouble();
     double occupancyRate = totalRoomsOccupied/totalRooms;

     System.out.println("The number of rooms vacant are" + vacant);
     System.out.println("Then occupancy rate is" + occupancyRate);

You have to move the rooms = input.nextInt(); into the while(rooms < 1) loop.

while(floors < 1); is equivalent to while(floors < 1){} so if you enter a number inferior than one, the loop will never end.

You have to take a new input in the while loop (and remove the ; after the while).

while(floors < 1){
      System.out.println("Invalid input. Enter again");
      floors = input.nextInt(); 
}

You have to do the same thing for the other while loop (don't forget to remove the ; after the while too) :

while(rooms < 1){
     System.out.println("Invalid entry. Enter again");
     rooms = input.nextInt();
}

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