Search code examples
javawhile-loopdoubleaddition

how to add together all doubles in a while loop, java


while (read.hasNext()) {

String roomType = read.nextLine();
int rooms = read.nextInt();
double price = read.nextDouble();
double roomIncome = (double) (rooms*price);
double tax = (double) (price*rooms*defaultTax);
double totalIncome = roomIncome;
roomIncome++; 
read.skip("\\s+");      



        
System.out.println("Room type: " + roomType + " | No. of rooms: " + rooms + " | Room price: " + price + " | income: " + roomIncome + " | tax: " + tax);

System.out.println("The total room income is: " + totalIncome);

I need to add together all the roomIncome's together to give a totalIncome output. Currently my output is:

Room type: Single | No. of rooms: 5 | Room price: 23.5 | income: 118.5 | tax: 23.5
The total room income is: 117.5
Room type: Double | No. of rooms: 3 | Room price: 27.5 | income: 83.5 | tax: 16.5
The total room income is: 82.5
Room type: Suite | No. of rooms: 2 | Room price: 50.0 | income: 101.0 | tax: 20.0
The total room income is: 100.0

my expected output should be the total of all roomIncome added together. So in this case it should add up to 300. Instead it has added 1 to roomIncome and given me an output of 100


Solution

  • If you want to print total income for all rooms types combined, you need to maintain variable outside the loop and keep on adding values inside the loop, as below:

    double allRoomsTotalIncome = 0.0;
    
    while (read.hasNext()) {
    
      String roomType = read.nextLine();
      int rooms = read.nextInt();
      double price = read.nextDouble();
      double roomIncome = (double) (rooms*price);
      double tax = (double) (price*rooms*defaultTax);
      double totalIncome = roomIncome;
      allRoomsTotalIncome = allRoomsTotalIncome + totalIncome;
      roomIncome++; 
      read.skip("\\s+");      
            
      System.out.println("Room type: " + roomType + " | No. of rooms: " + rooms + " | Room price: " + price + " | income: " + roomIncome + " | tax: " + tax);
    }
    
    
    
    System.out.println("The total room income is: " + allRoomsTotalIncome);