循环?我需要弄清楚如何解决这个问题。

时间:2013-11-02 10:31:56

标签: java

当我运行我的程序并尝试添加输入时。它一直说无效输入。再次输入。我知道为什么它做了b / c我添加了一个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);

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

while(floors < 1);相当于while(floors < 1){},因此如果您输入的数字低于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();
}