如何在while循环中修复此计数器?

时间:2014-03-22 17:17:31

标签: java while-loop counter

  //Name: Justin 

  import java.util.Scanner;

  public class hotelOccupancy
  {

  public static void main(String[] args)
  {

  Scanner keyboard = new Scanner(System.in);
  int floors, roomNo, occRooms, emptyRooms, occRoomsT = 0, roomNoT = 0;
  double occupancyRate;

  System.out.print("Enter the amount of floors in the hotel(must enter at least 1): ");
    floors = keyboard.nextInt();

  while(floors > 0)
     {
  System.out.print("Enter the amount of rooms on floor " + floors + ":");
    roomNo = keyboard.nextInt();

     if(roomNo < 10)
     {
  System.out.println("There is a minimum of 10 rooms per floor");
  System.out.print("Enter the amount of rooms on floor " + floors + ":");
    roomNo = keyboard.nextInt();
     }

  System.out.print("Enter the amount of rooms on floor " + floors + " that are occupied: ");
    occRooms = keyboard.nextInt();

     if(occRooms < 0 || occRooms > roomNo)
     {
  System.out.println("Please enter a valid number of occupied rooms");
  System.out.print("Enter the amount of rooms on floor " + floors + " that are occupied: ");
    occRooms = keyboard.nextInt();
     }

   occRoomsT = occRoomsT + occRooms;
   roomNoT = roomNoT + roomNo;  
   floors--;
   }

  occupancyRate = occRoomsT / roomNoT;
  emptyRooms = roomNoT - occRoomsT;

  System.out.println("The total amount of rooms is: " + roomNoT);
  System.out.println("The total amount of occupied rooms is: " + occRoomsT);
  System.out.println("The occupancy rate is: " + occupancyRate);
  System.out.println("The amount of vacant rooms is: " + emptyRooms);

  }
  }

你好,这个程序用于计算酒店的入住率,房间总数,占用房间总数和空房总数。输入是楼层数量,每层楼的房间数量以及给定楼层的占用房间数量。输入数据后,占用率总是达到0.0,这是我的问题。我有一种感觉,问题在于我的变量计数器名为:occRoomsT和roomNoT。

1 个答案:

答案 0 :(得分:0)

刚刚制作,

occupancyRate = ((double)occRoomsT) / roomNoT;

房间总数将始终为整数,并将它们声明为双倍并不是一个好习惯,与整数相比,这会占用更多空间。