Home > Net >  Creating an array of objects by parameters
Creating an array of objects by parameters

Time:09-17

I have 2 classes, the first class (PatientFlow) contains a constructor, a bunch of getMethods and a toString, no main. The first class cannot output or get read input, only through passed parameters. The second class (Patient) asks for the users inputs for some questions such as name, dob etc.. this class runs a bunch of methods aswell.

Patient p1 = new Patient(name,dob,address,gender,medicareNum,appDay,time); //Patient created
//is what is created with all users input and sent to the constructor class

Now my task is to create an array of patient(objects) within the first class (patientFlow).. but I don't understand how to do that... I've been seriously stuck on this for some days now and its driving me insane.. When I put the main() in the first class, I can't reference anything because of static..

public class Patient
{
  private String name, age, address, gender, time, appDay;
  private int medicareFinal;
  private boolean vaccination;
  public Patient (String name, String age, String address, String gender, int medicareFinal, String appDay, String time)
    {
    this.name = name;
    this.age = age;
    this.address = address;
    this.gender = gender;
    this.medicareFinal = medicareFinal;
    this.appDay = appDay;
    this.time = time; 
    }
  public String getName()
    { 
     return name;
    }
  public String getAddress()
    { 
     return address;
    }
  public String getGender()
    { 
     return gender;
    }
  public String getTime()
    { 
     return time;
    }
  public String getAge()
    {
     return age; 
    }
  public int getMedicare()
    {
     return medicareFinal;
    }
  public String getAppDay()
    {
     return appDay;
    }
  public String toString()
    { 
     String data; 
     data = "Patient Name: "  name   "\n";
     data  = "Age/Dob: "   age   "\n";
     data  = "Address: "   address   "\n";
     data  = "Gender: "   gender   "\n";
     data  = "Medicare Number: "   medicareFinal   "\n";
     data  = "Appointment Day: "   appDay   "\n";
     data  = "Appointment Time: "   time   "\n";
     return data;
    }
}

import java.time.*; // This is used to utilize dates/times
import java.util.*;
public class PatientFlow
{
   Patient p1, p2;
   Scanner scan=new Scanner(System.in); 
   enum weekdays {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday} //enumerated type for Task 4    
   public void readPatient1() //Details of first patient
     {
      System.out.println("Firstly, what is your full name?");
      String name = scan.nextLine(); 
      System.out.println(name   ", Please enter your date of birth in the correct format yyyy-mm-dd:");
      String dob = scan.nextLine();
      age(dob); //Calling age method to check if patient is older than 18
      System.out.println("What is your current residential address?"); 
      String address= scan.nextLine();
      System.out.println("Are you male or female?");
      String gender = scan.nextLine();
      System.out.println("What is your 8-digit Medicare number?");
      int medicareNum = scan.nextInt();
      int medicareFinal = medicare(medicareNum); //Calling medicare method to check if input = 8 numbers
      String shift = scan.nextLine();
      System.out.println("What day would you like to book the vaccination?");
      String appDay = scan.nextLine();
      weekdays(appDay); //Calling weekday method which checks availability through enumerated type
      System.out.println("What time would you like to book on "   appDay   "?");
      String time = scan.nextLine();
      p1 = new Patient(name,dob,address,gender,medicareNum,appDay,time); //Patient created
      System.out.println("You have booked in:");
      System.out.println("-----------------------------------------------"   "\n"   p1);
      System.out.println("-----------------------------------------------");
     }
   public void readPatient2() //Details for the second patient
     {
      System.out.println("Name of the person attending the second booking:");
      String name = scan.nextLine(); 
      System.out.println(name   ", Please enter your date of birth in the correct format yyyy-mm-dd:");
      String dob = scan.nextLine();
      age(dob); //Calling age method to check if patient is older than 18
      System.out.println("What is your current residential address?"); 
      String address= scan.nextLine();
      System.out.println("Are you male or female?");
      String gender = scan.nextLine();
      System.out.println("What is your 8 digit medicare number?");
      int medicareNum = scan.nextInt();
      int medicareFinal = medicare(medicareNum); //Calling medicare method to check if input = 8 numbers
      String shift = scan.nextLine(); //Using this to catch the users 'enter' input
      System.out.println("What day would you like to book the vaccination?");
      String appDay = scan.nextLine();
      weekdays(appDay); //Calling weekday method which checks availability through enumerated type
      System.out.println("What time would you like to book on "   appDay   "?");
      String time = scan.nextLine();
      p2 = new Patient(name,dob,address,gender,medicareNum,appDay,time); //Patient created
      System.out.println("Thank you for using this online booking service.");
      System.out.println("You have booked in:");
      System.out.println("-----------------------------------------------"   "\n"   p2);
      System.out.println("-----------------------------------------------");
     }
   public void age(String dob) //Method for DOB
     {
      Scanner scan = new Scanner(System.in); //Retrieving User inputs
      String answer, consent;
      LocalDate dateOfBirth = LocalDate.parse(dob); // Convert string input to date format
      LocalDate currDate = LocalDate.now(); // Get todays date: yyyy-mm-dd
      Period period = Period.between(currDate, dateOfBirth); // Get the difference between the two dates
      int age  = Math.abs(period.getYears()); // Isolate the number of years to get proper age format
      if (age < 18)
      {
        System.out.println("Sorry, because you are "   age   " years old, it is illegal to book you an appointment. You must be 18 to book this service.");
        System.out.println("If an adult is with you, type 'yes' to continue. If not, try booking again later. Thank you");
        answer = scan.nextLine();
        if (answer.equals("yes"))
        {
          System.out.println("Continuing booking process...");
        } else
        {
          System.out.println("You need an adult with you in order to continue this booking.");
          System.exit(0);   //Terminates if person is under 18 without adult
        }
      } //returning values
     }
   public static int medicare(int medicareNum) //Method for medicare
     {
       Scanner scan = new Scanner(System.in);
       String correct, shift;
       int medicareFinal = medicareNum;
       int medicaretemp;
       int length = String.valueOf(medicareNum).length(); // Int conversion to string length
       if (length == 8) // If statement to proceed with correct detail
       {
         System.out.println(medicareNum  ", Are you sure this is the correct number? This information is very important. 'yes' or 'no'");
         correct = scan.nextLine();
         if (correct.equals("yes")) // Nested if statement
         {                     
           System.out.println("Thank you, please continue with the booking");
           medicareFinal = medicareNum;
         } else
         {
           length = 0;
         }
       }
       while (length != 8) // while loop to get correct size of input 
        {   System.out.println("You haven't input the correct amount of numbers in. Please try again.");
            medicaretemp = scan.nextInt();
            medicareFinal = medicaretemp;
            shift = scan.nextLine(); //Using this to catch the users 'enter' input
            int lengthNew = String.valueOf(medicaretemp).length(); // Conversion of int to String
            if (lengthNew == 8)
            {
              System.out.println(medicaretemp  ", Is this new number correct? This information is very important. 'yes' or 'no'");
              correct = scan.nextLine();
              if (correct.equals("yes"))
              {
                medicareFinal = medicaretemp;
                System.out.println("Thank you, please continue with the booking");
                break; //Breaking loop if requirement is met
              } else
              {
                length = 0;
              }
            }
        } 
        return medicareFinal; // return value
    }
   public void weekdays(String appDay)
     {    
      boolean dayAvail = false;
      for(weekdays day : weekdays.values())
         {
          if (appDay.equalsIgnoreCase(day.name())) 
          {
            dayAvail = true;
            System.out.println(appDay   " is available for your appointment.");
            break;
          }
         }
      if (!dayAvail)
      {
        System.err.println( "This day is not available.." ); // Shows error message, will put exception in there for Assignment 3      
      } 
     }
   public void confirmation()
     {
      int answer;
      String shift;
      System.out.println("Are the details correct for both patients or do they need modifying?");
      System.out.println("Press '1' to modify "   p1.getName()   ", press '2' to modify "   p2.getName()   ", or press 3 to complete booking");
      answer = scan.nextInt();
      shift = scan.nextLine(); //Using this to catch the users 'enter' input
      if (answer==1)
      {
        readPatient1(); //Calls back to Patient 1 method
        confirmation();
      }
      if (answer==2)
      {
        readPatient2(); //Calls back to Patient 2 method
        confirmation();
      }
      if (answer==3)
      {
        System.out.println("Thank you for using this online booking service.");
        System.out.println("You have booked in:");
        System.out.println("-----------------------------------------------"   "\n"   p1);
        System.out.println("-----------------------------------------------"   "\n"   p2);
        System.out.println("-----------------------------------------------");
        System.out.println("Remember to come 10 minutes early and sign in with the appropriate applications! Both appointments will be held at the AIS");
        System.exit(0); //Exit program when user is happy with details
      }
     }
   public void PatientBook()
     {
      String answer;
      System.out.println("\n");
      System.out.println("Would you like to add another appointment? 'yes' or 'no'");
      answer = scan.nextLine();
      switch (answer) //Using a switch to dictate which methods are required next
        {
          case ("yes"):
              readPatient2();
              confirmation();
          case ("no"):
                System.out.println("Thank you for using this online booking service.");
         System.out.println("You have booked in:");
         System.out.println("-----------------------------------------------"   "\n"   p1);
         System.out.println("-----------------------------------------------");
         System.out.println("Remember to come 10 minutes early and sign in with the appropriate applications! Your appointment will be held at the AIS");
         System.exit(0);
        }
     }
   public void init() //method to call all methods when required
     {
      start();
      readPatient1();
      PatientBook();
      readPatient2();
      confirmation();
     }
   public static void main(String [] args)
     {
      PatientFlow pf = new PatientFlow(); //Creating the object
      pf.init();
     }
}

any help would be much appreciated, or a tag in some videos

TIA

CodePudding user response:

// imports

public class PatientFlow {
   private Patient[] patients;
   public PatientFlow(){
      // init array
   }
    
   // other prop
   //  getter & setter
}

CodePudding user response:

By the way, in current Java 17, you can reduce that entire Patient class to a simple line using the records feature.

record Patient ( String name, String age, String address, String gender, int medicareFinal, String appDay, String time ) {}

You do not need your enum weekdays. Java provides DayOfWeek enum.

I don’t understand the meaning of multiple readPatient1() methods. You should be looping on a single method repeatedly until the user wants to stop.

You said:

Now my task is to create an array of patient(objects) within the first class (patientFlow)

So declare a member field in that class. Size the array to the most number of patients you will book.

Patient[] patients = new Patient[ 12 ] ;

First patient goes into the first slot identified by a zero-based index number.

patients[ 0 ] = new Patient( … ) ;

Increment an index number in your loop to repeatedly add patients. Name your index number something like int index = 0 ;

patients[ index ] = new Patient( … ) ;

FYI, in real work we would likely use a List rather than a mere array.

As for static, you are probably having a problem in your main method which I don’t see here. And that problem is almost certainly a duplicate of many existing Questions already answered on Stack Overflow. Always search before posting.

  • Related