0

当我运行我的程序并尝试添加输入时。它一直说无效输入。再次输入。我知道为什么 b/ci 添加了一个 while 循环,但那是针对小于 1 的输入。我该如何解决这个问题?我需要显示入住率和空房数量。我是初学者,所以我认为我犯了一个愚蠢的错误。有人可以帮助我吗?

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);
4

2 回答 2

1

您必须将其移动rooms = input.nextInt();while(rooms < 1)循环中。

于 2013-11-02T10:34:53.367 回答
0

while(floors < 1);相当于while(floors < 1){}so如果你输入一个小于1的数字,循环将永远不会结束。

您必须在 while 循环中获取新输入(并在;while 之后删除)。

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

你必须对另一个while循环做同样的事情(不要忘记;在while之后删除):

while(rooms < 1){
     System.out.println("Invalid entry. Enter again");
     rooms = input.nextInt();
}
于 2013-11-02T10:34:52.597 回答