Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java College practice

Tags:

java

I am a Java beginner and also new to this site. I am learning about arrays and methods and unfortunately I am stuck The question is:

A hospital has space for 150 patients. Each room has a space for 3 patients.
The hospital charges a patient $150 to stay. If each room is occupied by 3 patients, the hospital charges an additional $50. Prompt the user for number of patients and display the total number of patients, grand total amount of all charges.

In my opinion, I would like to create a parallel array of the number of rooms and another array of number of patients for each room.

The problem is: Every time the program asks the following. Enter # of patients for room 0 Enter # of patients for room 0 Enter # of patients for room 0 Instead of: Enter # of patients for room #1 Enter # of patients for room #2 Enter # of patients for room #3

So I believe it is a logic error because roomNumbers[i] is not getting updated to room 1 ,room2,etc it only asks for room 0 all the time, please every advise is welcome as I am just starting on this new course for the next semester. Does my logic even makes sense? Thank you very much.

import javax.swing.JOptionPane;

public class Pingo {
    public static void main(String[] args) {
        final int MAXROOMS=50;
        int[] roomNumbers = new int[MAXROOMS];  
        int [] patientQuantity = new int [roomNumbers.length];
        int numPatients=getNumberOfPatients(roomNumbers,patientQuantity);
    }


    public static int getNumberOfPatients(int[] roomNumbers, int []patientQuantity){
        int numPatients=0;

        for(int i=0; i<patientQuantity.length; i++){
            numPatients=Integer.parseInt(JOptionPane.showInputDialog("Enter amount of Patients for room:"
                    + roomNumbers[i] ));
            patientQuantity[i]=numPatients;                                    
        }  
        return numPatients;  
    }                                     
}   
like image 655
Atari16 Avatar asked Dec 24 '15 00:12

Atari16


1 Answers

The problem is here:

int[] roomNumbers = new int[MAXROOMS];

Your are declaring an array and initializing it. The problem is that the values in the array are all zero. That is because when you allocate an array using new the element values will be default initialized according to the array basetype:

  • Numeric types have a default initial value of zero.
  • The bool type has a default initial value of false.
  • Reference types (classes and array types) have a default initial value of null.

There are two simple solutions here:

  • Set initial values for each array element; e.g. using a loop.
  • Don't use an array to hold the room numbers; e.g. do some simple arithmetic and use your index variable (i) to calculate the room number. (Think about it ...)
like image 90
Stephen C Avatar answered Sep 26 '22 14:09

Stephen C