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;
}
}
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:
bool
type has a default initial value of false
.null
.There are two simple solutions here:
i
) to calculate the room number. (Think about it ...)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With