Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This program is supposed to be a log of patients in a hospital, but it is not ru

ID: 3801888 • Letter: T

Question

This program is supposed to be a log of patients in a hospital, but it is not running. there is an error message coming from line 21 that reads, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

public class HospitalManagement {
      
       public static void main(String args[]) throws IOException {
           String inputFileName = "/home/zubair/Desktop/a.txt";
           new HospitalManagement(inputFileName);
       }

       private PatientList patientLogData;
      
       public HospitalManagement(String inputFilePath) throws IOException {
           patientLogData = loadFromFile(inputFilePath);
           start();
       }
      
       public void start() throws IOException {
           Scanner scanner = new Scanner(System.in);          
          
           while (true) {
               displayMenu();
               String choice = scanner.nextLine().toUpperCase();
              
               switch(choice) {
                   case "A" :
                       displayList();
                       break;
                      
                   case "B" :
                       addNewPatient(scanner);
                       break;
                      
                   case "C" :
                       showInfoOfAPatient(scanner);
                       break;
                      
                   case "D" :
                       deleteAPatient(scanner);
                       break;
                      
                   case "E" :
                       showAverageAgeOfPatient();
                       break;
                      
                   case "F" :
                       showInfoOfYoungestPatient();
                       break;
                      
                   case "G" :
                       showNotificationList();
                       break;
                      
                   case "H" :
                       Quit(scanner);
                       scanner.close();
                       return;
                   default :
                       System.out.println(System.lineSeparator());
                       System.out.println("Invalid Choice");  
                       System.out.println(System.lineSeparator());
               }
           }
       }
      
       private void displayList() {
           List<PatientInfo> patientList = patientLogData.getList();
           for (PatientInfo patient : patientList) {
               System.out.println(patient.getName() + " " + patient.getId());
           }
       }

       private void deleteAPatient(Scanner scanner) {
           System.out.println("Enter id of the patient : ");
           String id = scanner.nextLine();
           patientLogData.remove(id);
       }

      
       @SuppressWarnings("deprecation")
       private void showAverageAgeOfPatient() {          
           List<PatientInfo> patientList = patientLogData.getList();
           Date currDate = new Date(System.currentTimeMillis());

           int averageAge = 0;
           for (PatientInfo patient : patientList) {
               averageAge += (currDate.getYear() - patient.getDateOfBirth().getYear());
           }
           if (patientList.size()!=0)
               averageAge /= patientList.size();
          
           System.out.println(System.lineSeparator());
           System.out.println("Average age of the patients is : "+ averageAge + " years");
           System.out.println(System.lineSeparator());
       }

       private void showInfoOfAPatient(Scanner scanner) {
           System.out.println("Enter id of the patient : ");
           String id = scanner.nextLine();
           PatientInfo patient = patientLogData.find(id);
           if (patient != null) {
               System.out.println(patient.toString());
           }
           else {
               System.out.println("paitent not found");
           }
           System.out.println(System.lineSeparator());

       }

       @SuppressWarnings("deprecation")
       private void showInfoOfYoungestPatient() {
           List<PatientInfo> patientList = patientLogData.getList();
           Date currDate = new Date(System.currentTimeMillis());

           if (patientList.size() <= 0) {
               System.out.println(System.lineSeparator());
               System.out.println("No patient data is available");
               return;
           }
           PatientInfo youngPatient = patientList.get(0);
           int smallest = (currDate.getYear() - youngPatient.getDateOfBirth().getYear());

           for (PatientInfo patient : patientList) {
               int age = (currDate.getYear() - patient.getDateOfBirth().getYear());
               if (age < smallest) {
                   smallest = age;
                   youngPatient = patient;
               }
           }
          
           System.out.println(System.lineSeparator());
           System.out.println("Youngest patient is : "+ youngPatient);
           System.out.println(System.lineSeparator());
       }

       @SuppressWarnings("deprecation")
       private void showNotificationList() {
           List<PatientInfo> patientList = patientLogData.getList();
           Date currDate = new Date(System.currentTimeMillis());

           for (PatientInfo patient : patientList) {
               int time = (currDate.getYear() - patient.getLastVisit().getYear());
               if (time >= 3) {
                   System.out.println(patient.getId()+", "+patient.getName()+", is overdue for a visit , been " + time + " years");
               }
           }
       }

       private void addNewPatient(Scanner scanner) {
          
       }

       public void Quit(Scanner sc) throws IOException {
           System.out.println(System.lineSeparator());
           System.out.print("Do you wan to write the output (Y/N)? : ");
          
           while (true) {
               String userChoice = sc.nextLine();
              
               if (userChoice.equalsIgnoreCase("Y")) {
                   System.out.print("Enter output file : ");
                   writeBackToFile(sc.nextLine(), patientLogData);
                   return;
               }
               else if (userChoice.equalsIgnoreCase("N")) {
                   return;
               }
               else {
                   System.out.println("Invalid Option");
                   System.out.println(System.lineSeparator());
               }
           }
       }
      
       /**
       * Reads the patient data from a given file
       * @param filePath
       * @return
       * @throws IOException
       */
       public PatientList loadFromFile(String filePath) throws IOException {
           PatientList patientLogData = new PatientList();
           BufferedReader bufferedInput = new BufferedReader(new FileReader(filePath));
          
           String inputLine;
           while ((inputLine = bufferedInput.readLine()) != null) {
               String[] patientData = inputLine.split(" ");
              
               String id = patientData[0];
               String name = patientData[1];
               Date doB = new Date(Long.valueOf(patientData[2]));
               String address = patientData[3];
               int height = Integer.valueOf(patientData[4]);
               double weight = Double.valueOf(patientData[5]);
               Date lastVisit = new Date(Long.valueOf(patientData[6]));          
               Date initialVisit = new Date(Long.valueOf(patientData[7]));
              
               PatientInfo patient = new PatientInfo(name, id, doB, address, height, weight, initialVisit, lastVisit);
               patientLogData.add(patient);
           }
          
           bufferedInput.close();
           return patientLogData;
       }

      
       /**
       * Writes the output to a file
       * @param filePath
       * @param patientList
       * @throws IOException
       */
       public void writeBackToFile(String filePath, PatientList patientList) throws IOException {
           if (filePath == null || filePath.isEmpty()) {
               return;
           }
           BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
          
           for (PatientInfo patient : patientList.getList()) {
               String id = patient.getId();
               String name = patient.getName();
               int height = patient.getHeight();
               double weight = patient.getWieght();
               String address = patient.getAddress().replaceAll(" ", "-");
               Date doB = patient.getDateOfBirth();
               Date lastVisit = patient.getLastVisit();              
               Date initialVisit = patient.getIntialVisit();
               bufferedWriter.write(id + " " + name + " " + doB.getTime() + " " + address + " " + height + " " + weight
                   + " " + lastVisit.getTime() + " " + initialVisit.getTime() + " ");
           }
           bufferedWriter.close();
       }
      
       public void displayMenu() {  
           System.out.println(System.lineSeparator());
           System.out.println(System.lineSeparator());
           System.out.println("Menu");
           System.out.println("A.Display List");
           System.out.println("B.Add a new patient");
           System.out.println("C.Show info for a patient");          
           System.out.println("D.Delete a patient");          
           System.out.println("E.Show average age of patient");          
           System.out.println("F.Show info of youngest patient");
           System.out.println("G.Show notification list");
           System.out.println("H.Quit");
           System.out.print("Enter your choice : " );
       }
      
}

class PatientList {

   private List<PatientInfo> patientList;
  
   public PatientList() {
       patientList = new ArrayList<>();
   }
  
   public List<PatientInfo> getList() {
       return patientList;
   }
  
   public PatientInfo find(String patientID) {
       for (PatientInfo patient : patientList) {
           if (patient.getId().equalsIgnoreCase(patientID)) {
               return patient;
           }
       }
       return null;
   }
  
   public int find(PatientInfo inputPatient) {
       int i=0;
       for (PatientInfo patient : patientList) {
           if (patient.getId().equalsIgnoreCase(inputPatient.getId())) {
               return i;
           }
           i++;
       }
       return -1;
   }
  
   public void remove(String patientID) {
       PatientInfo element = null;
       for (PatientInfo patient : patientList) {
           if (patient.getId().equalsIgnoreCase(patientID)) {
               element = patient;
               break;
           }
       }
       if (element != null) {
           patientList.remove(element);
       }
   }

   public boolean contains(PatientInfo patient) {
       if (find(patient.getId()) == null) {
           return false;
       }
       return true;
   }

   public void remove(PatientInfo patient) {
       patientList.remove(patient);
   }

   public void add(PatientInfo patient) {
       patientList.add(patient);
   }

   public int size() {
       return patientList.size();
   }
  
   @Override
   public String toString() {
       StringBuffer buffer = new StringBuffer();
       for (PatientInfo patient : patientList) {
           buffer.append(patient.toString() + System.lineSeparator());
       }
       return buffer.toString();
   }
}

class PatientInfo {
  
   private String name;
   private String id;
   private Date dateOfBirth;
   private String address;
   private int height;
   private double wieght;
   private Date intialVisit;
   private Date lastVisit;
  
   public PatientInfo(String name, String id, Date dateOfBirth, String address, int height, double wieght,
           Date intialVisit, Date lastVisit) {
       super();
       this.name = name;
       this.id = id;
       this.dateOfBirth = dateOfBirth;
       this.address = address;
       this.height = height;
       this.wieght = wieght;
       this.intialVisit = intialVisit;
       this.lastVisit = lastVisit;
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

   public String getId() {
       return id;
   }

   public void setId(String id) {
       this.id = id;
   }

   public String getAddress() {
       return address;
   }

   public void setAddress(String address) {
       this.address = address;
   }

   public int getHeight() {
       return height;
   }

   public void setHeight(int height) {
       this.height = height;
   }

   public double getWieght() {
       return wieght;
   }

   public void setWieght(double wieght) {
       this.wieght = wieght;
   }

   public Date getDateOfBirth() {
       return dateOfBirth;
   }

   public void setDateOfBirth(Date dateOfBirth) {
       this.dateOfBirth = dateOfBirth;
   }

   public Date getIntialVisit() {
       return intialVisit;
   }

   public void setIntialVisit(Date intialVisit) {
       this.intialVisit = intialVisit;
   }

   public Date getLastVisit() {
       return lastVisit;
   }

   public void setLastVisit(Date lastVisit) {
       this.lastVisit = lastVisit;
   }

   @Override
   public String toString() {
       return "PatientInfo [name=" + name + ", id=" + id + ", address=" + address + ", height=" + height + ", wieght="
               + wieght + ", dateOfBirth=" + dateOfBirth + ", intialVisit=" + intialVisit + ", lastVisit=" + lastVisit+ "]";
   }
}

Explanation / Answer

Since a.txt input file is not provided in the question, it is a bit difficult to point out which record is causing the error. Some record in the file has a single word on the line and nothing else following it. It could mostly be the last line. But it could be any line in between too. So to assist you which line is causing that, I have modified the loadfromfile() function to display the line number of input fie thatit is processing. So it will show you exactly which line is throwing that exception. The exception is thrown because the required number of fields are not there is one of the records.

Also to test out the other parts of the code, I just loaded the program with an emtpy a.txt file and then created a patient record and other options as well (By the way , I have implemented the code to add a patient , that function was not coded earlier ). Later I wrote back the file to a.txt. In the next run of the program, the program loaded the single record I created previously. So rest of the code looks fine. I am attaching the sample run of program with empty a.txt file. The file should be there on system, but can be empty.

Also you can try to paste the a.txt contents shown below in this answer into a separate file and try loading it by specifying this new filename in your program. If the program runs perfect, then it confirms that the original a.txt in your local system has a improper record structure.

In case the "processing line " message did not help you, request you to edit this question and paste the contents of the a.txt file here so that I can exactly find out the reason why code is failing. Please do post a comment in either case whether or not the problem is resolved. If problem is resolved and the answer helped, request you to rate the answer. Thank you very much.

Here is the update HospitalManagement.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
public class HospitalManagement {
  
public static void main(String args[]) throws IOException {
String inputFileName = "a.txt";
new HospitalManagement(inputFileName);
}
private PatientList patientLogData;
  
public HospitalManagement(String inputFilePath) throws IOException {
patientLogData = loadFromFile(inputFilePath);
start();
}
  
public void start() throws IOException {
Scanner scanner = new Scanner(System.in);
  
while (true) {
displayMenu();
String choice = scanner.nextLine().toUpperCase();
  
switch(choice) {
case "A" :
displayList();
break;
  
case "B" :
addNewPatient(scanner);
break;
  
case "C" :
showInfoOfAPatient(scanner);
break;
  
case "D" :
deleteAPatient(scanner);
break;
  
case "E" :
showAverageAgeOfPatient();
break;
  
case "F" :
showInfoOfYoungestPatient();
break;
  
case "G" :
showNotificationList();
break;
  
case "H" :
Quit(scanner);
scanner.close();
return;
default :
System.out.println(System.lineSeparator());
System.out.println("Invalid Choice");
System.out.println(System.lineSeparator());
}
}
}
  
private void displayList() {
List<PatientInfo> patientList = patientLogData.getList();
for (PatientInfo patient : patientList) {
System.out.println(patient.getName() + " " + patient.getId());
}
}
private void deleteAPatient(Scanner scanner) {
System.out.println("Enter id of the patient : ");
String id = scanner.nextLine();
patientLogData.remove(id);
}
  
@SuppressWarnings("deprecation")
private void showAverageAgeOfPatient() {
List<PatientInfo> patientList = patientLogData.getList();
Date currDate = new Date(System.currentTimeMillis());
int averageAge = 0;
for (PatientInfo patient : patientList) {
averageAge += (currDate.getYear() - patient.getDateOfBirth().getYear());
}
if (patientList.size()!=0)
averageAge /= patientList.size();
  
System.out.println(System.lineSeparator());
System.out.println("Average age of the patients is : "+ averageAge + " years");
System.out.println(System.lineSeparator());
}
private void showInfoOfAPatient(Scanner scanner) {
System.out.println("Enter id of the patient : ");
String id = scanner.nextLine();
PatientInfo patient = patientLogData.find(id);
if (patient != null) {
System.out.println(patient.toString());
}
else {
System.out.println("paitent not found");
}
System.out.println(System.lineSeparator());
}
@SuppressWarnings("deprecation")
private void showInfoOfYoungestPatient() {
List<PatientInfo> patientList = patientLogData.getList();
Date currDate = new Date(System.currentTimeMillis());
if (patientList.size() <= 0) {
System.out.println(System.lineSeparator());
System.out.println("No patient data is available");
return;
}
PatientInfo youngPatient = patientList.get(0);
int smallest = (currDate.getYear() - youngPatient.getDateOfBirth().getYear());
for (PatientInfo patient : patientList) {
int age = (currDate.getYear() - patient.getDateOfBirth().getYear());
if (age < smallest) {
smallest = age;
youngPatient = patient;
}
}
  
System.out.println(System.lineSeparator());
System.out.println("Youngest patient is : "+ youngPatient);
System.out.println(System.lineSeparator());
}
@SuppressWarnings("deprecation")
private void showNotificationList() {
List<PatientInfo> patientList = patientLogData.getList();
Date currDate = new Date(System.currentTimeMillis());
for (PatientInfo patient : patientList) {
int time = (currDate.getYear() - patient.getLastVisit().getYear());
if (time >= 3) {
System.out.println(patient.getId()+", "+patient.getName()+", is overdue for a visit , been " + time + " years");
}
}
}
private void addNewPatient(Scanner scanner) {
   String name,id,address;
   Date dob,lastvisit,initialvisit;
   int height;
   double weight;
   SimpleDateFormat dateFormatter=new SimpleDateFormat("dd-MMM-yyyy");
   System.out.println("Enter the patient details ");
   System.out.println("ID: ");
   id=scanner.nextLine();
   System.out.println("Name: ");
   name=scanner.nextLine();
   System.out.println("Address: ");
   address=scanner.nextLine();
   System.out.println("Height: ");
   height=scanner.nextInt();
   System.out.println("Weight: ");
   weight=scanner.nextDouble();
  
   System.out.println("Date of Birth(dd-MMM-yyyy): ");
   try {
       dob=dateFormatter.parse(scanner.next());
  
           System.out.println("Initial Visit date (dd-MMM-yyyy): ");          
           initialvisit=dateFormatter.parse(scanner.next());
          
           System.out.println("Last Visit date(dd-MMM-yyyy): ");
           lastvisit=dateFormatter.parse(scanner.next());   
      
           patientLogData.add(new PatientInfo(name, id, dob, address, height, weight, initialvisit, lastvisit));
   } catch (ParseException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
}
public void Quit(Scanner sc) throws IOException {
System.out.println(System.lineSeparator());
System.out.print("Do you wan to write the output (Y/N)? : ");
  
while (true) {
String userChoice = sc.nextLine();
  
if (userChoice.equalsIgnoreCase("Y")) {
System.out.print("Enter output file : ");
writeBackToFile(sc.nextLine(), patientLogData);
return;
}
else if (userChoice.equalsIgnoreCase("N")) {
return;
}
else {
System.out.println("Invalid Option");
System.out.println(System.lineSeparator());
}
}
}
  
/**
* Reads the patient data from a given file
* @param filePath
* @return
* @throws IOException
*/
public PatientList loadFromFile(String filePath) throws IOException {
PatientList patientLogData = new PatientList();
BufferedReader bufferedInput = new BufferedReader(new FileReader(filePath));
int line=1;
String inputLine;
while ((inputLine = bufferedInput.readLine()) != null) {
System.out.println("processing line "+line);
   String[] patientData = inputLine.split(" ");
  
String id = patientData[0];
String name = patientData[1];
Date doB = new Date(Long.valueOf(patientData[2]));
String address = patientData[3];
int height = Integer.valueOf(patientData[4]);
double weight = Double.valueOf(patientData[5]);
Date lastVisit = new Date(Long.valueOf(patientData[6]));
Date initialVisit = new Date(Long.valueOf(patientData[7]));
  
PatientInfo patient = new PatientInfo(name, id, doB, address, height, weight, initialVisit, lastVisit);
patientLogData.add(patient);
line++;
}
  
bufferedInput.close();
return patientLogData;
}
  
/**
* Writes the output to a file
* @param filePath
* @param patientList
* @throws IOException
*/
public void writeBackToFile(String filePath, PatientList patientList) throws IOException {
if (filePath == null || filePath.isEmpty()) {
return;
}
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
  
for (PatientInfo patient : patientList.getList()) {
String id = patient.getId();
String name = patient.getName();
int height = patient.getHeight();
double weight = patient.getWieght();
String address = patient.getAddress().replaceAll(" ", "-");
Date doB = patient.getDateOfBirth();
Date lastVisit = patient.getLastVisit();
Date initialVisit = patient.getIntialVisit();
bufferedWriter.write(id + " " + name + " " + doB.getTime() + " " + address + " " + height + " " + weight
+ " " + lastVisit.getTime() + " " + initialVisit.getTime() + " ");
}
bufferedWriter.close();
}
  
public void displayMenu() {
System.out.println(System.lineSeparator());
System.out.println(System.lineSeparator());
System.out.println("Menu");
System.out.println("A.Display List");
System.out.println("B.Add a new patient");
System.out.println("C.Show info for a patient");
System.out.println("D.Delete a patient");
System.out.println("E.Show average age of patient");
System.out.println("F.Show info of youngest patient");
System.out.println("G.Show notification list");
System.out.println("H.Quit");
System.out.print("Enter your choice : " );
}
  
}

sample run with empty a.txt

Menu
A.Display List
B.Add a new patient
C.Show info for a patient
D.Delete a patient
E.Show average age of patient
F.Show info of youngest patient
G.Show notification list
H.Quit
Enter your choice : a


Menu
A.Display List
B.Add a new patient
C.Show info for a patient
D.Delete a patient
E.Show average age of patient
F.Show info of youngest patient
G.Show notification list
H.Quit
Enter your choice : b
Enter the patient details
ID:
h001
Name:
john
Address:
222 california
Height:
150
Weight:
158
Date of Birth(dd-MMM-yyyy):
12-jan-1980
Initial Visit date (dd-MMM-yyyy):
23-mar-2016
Last Visit date(dd-MMM-yyyy):
15-nov-2016


Menu
A.Display List
B.Add a new patient
C.Show info for a patient
D.Delete a patient
E.Show average age of patient
F.Show info of youngest patient
G.Show notification list
H.Quit
Enter your choice :

Invalid Choice


Menu
A.Display List
B.Add a new patient
C.Show info for a patient
D.Delete a patient
E.Show average age of patient
F.Show info of youngest patient
G.Show notification list
H.Quit
Enter your choice : a
john h001


Menu
A.Display List
B.Add a new patient
C.Show info for a patient
D.Delete a patient
E.Show average age of patient
F.Show info of youngest patient
G.Show notification list
H.Quit
Enter your choice : c
Enter id of the patient :
h001
PatientInfo [name=john, id=h001, address=222 california, height=150, wieght=158.0, dateOfBirth=Sat Jan 12 00:00:00 IST 1980, intialVisit=Wed Mar 23 00:00:00 IST 2016, lastVisit=Tue Nov 15 00:00:00 IST 2016]


Menu
A.Display List
B.Add a new patient
C.Show info for a patient
D.Delete a patient
E.Show average age of patient
F.Show info of youngest patient
G.Show notification list
H.Quit
Enter your choice : e


Average age of the patients is : 37 years


Menu
A.Display List
B.Add a new patient
C.Show info for a patient
D.Delete a patient
E.Show average age of patient
F.Show info of youngest patient
G.Show notification list
H.Quit
Enter your choice : f


Youngest patient is : PatientInfo [name=john, id=h001, address=222 california, height=150, wieght=158.0, dateOfBirth=Sat Jan 12 00:00:00 IST 1980, intialVisit=Wed Mar 23 00:00:00 IST 2016, lastVisit=Tue Nov 15 00:00:00 IST 2016]


Menu
A.Display List
B.Add a new patient
C.Show info for a patient
D.Delete a patient
E.Show average age of patient
F.Show info of youngest patient
G.Show notification list
H.Quit
Enter your choice : g


Menu
A.Display List
B.Add a new patient
C.Show info for a patient
D.Delete a patient
E.Show average age of patient
F.Show info of youngest patient
G.Show notification list
H.Quit
Enter your choice : h


Do you wan to write the output (Y/N)? : y
Enter output file : a.txt

a.txt after program exited

h001 john 316463400000 222-california 150 158.0 1479148200000 1458671400000

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote