Static Suggestion. What am I doing wrong? - java

So I am trying to pass an ArrayList to my main method, but eclipse is telling me I need to change my arraylist to a static. I know I'm doing something wrong but I can't figure it out.
ArrayList<Patient> pList = Doctor.getPatientList();
this is the call I have in my main method.
public class Doctor {
public ArrayList<Patient> patientList = new ArrayList<Patient>();
}
public void loadPatientData() {
BufferedReader read2 = null;
try {
read2 = new BufferedReader(new FileReader("data/patient_list.txt"));
String line;
while ((line = read2.readLine()) != null) {
line = read2.readLine();
if (line == null) {
break;
}
String[] lineValues = line.split(","); //split the string on this value into array
String firstName = lineValues[0];
String lastName = lineValues[1];
String address = lineValues[2];
String city = lineValues[3];
String state = lineValues[4];
String zip = lineValues[5];
String ssn = lineValues[6];
String genderNeedsConvert = lineValues[7];
String weightNeedsDouble = lineValues[8];
String heightNeedsDouble = lineValues[9];
String symptomsNotReady = lineValues[10]; // these need to be broken up further (using semicolons)
char gender = genderNeedsConvert.charAt(0);
double weight = Double.parseDouble(weightNeedsDouble);
double height = Double.parseDouble(heightNeedsDouble);
Patient patient = new Patient(firstName, lastName, address, city, state, zip, ssn, gender, weight, height, symptomsNotReady);
patientList.add(patient); // must be of patient type.
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (read2 != null) {
try {
read2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public ArrayList<Patient> getPatientList() {
return patientList;
}
This is a shortened version of my Doctor class.
public class Patient {
private String patientID;
private String firstName;
private String lastName;
private String ssn;
private char gender;
private String address;
private String city;
private String state;
private String symptoms;
private String zip;
public ArrayList<Diagnosis> diagnoses = new ArrayList<Diagnosis>();
//private Diagnosis diagnoses = new Diagnosis(0, null);// new diagnoses called as Diagnoses datatype
public ArrayList<Medication> newMedication = new ArrayList<Medication>();
//private Medication newMedication = new Medication(0, null);// newMedication called as medication datatype
ArrayList<String> symptom = new ArrayList<String>();
ArrayList<String> symptomCompare = new ArrayList<String>();
private double weight;
private double height;
int k = 0;
public Patient(String firstName,String lastName,String address,String city, String state,String zip,String ssn,char gender,double weight,double height,String symptoms){
this.firstName = firstName;
this.lastName = lastName;
this.ssn = ssn;
this.gender = gender;
this.weight = weight;
this.height = height;
this.address = address;
this.city = city;
this.state = state;
this.symptoms = symptoms;
this.zip = zip;
this.patientID = ssn.replace("-", ""); // removes dashes from ssn and sets the value to patientID
this.patientID = this.patientID.replace(" ", ""); //removes spaces from patientID
this.patientID = this.patientID + this.firstName.substring(0, 1) + this.lastName.substring(0, 1);
}
and above is the shortened patient class. I've been sitting here for a few hours trying different things but it keeps telling me to change the getPatientList() method to static. What am I doing wrong?

Doctor.getPatientList() is the syntax for calling a static method, since Doctor is a class name.
If you want to call an instance method (and getPatientList() is currently an instance method), you should call it using an instance of a Doctor:
Doctor doctor = new Doctor();
ArrayList<Patient> pList = doctor.getPatientList();

What ever variables/method you declare as static as known as class members. Strictly speaking, they belongs to the class instead of being an object's attribute.
When a variable is static, it exist even before the object is created. So what does that means?
Static methods can access static variables/methods.
Static methods cannot access non-static variables/methods. (because they don't exist)
If you want to let static methods access non-static variables/methods. One of the ways is to instantiate(create) the object which the method/variable you wanted to access belong to that object first.
The reason you need to instantiate first before you can access it is because you want to make them exist first. Class itself is only a blueprint, you need to create an object (to make them exist) before you can interact with it.
Example:
Doctor doctor = new Doctor();
ArrayList<Patient> list = doctor.patientList;
//Only possible if patientList is not private
If patientList is private in Class Doctor, you need to use a getter:
Doctor doctor = new Doctor();
ArrayList<Patient> list = doctor.getPatientList();
//getPateientList is a method in Doctor class

Use static modifier with public ArrayList<Patient> getPatientList():
public static ArrayList getPatientList()
You are invoking this method on class Doctor, and thus this method must be declared static.

You have to declare the class object first then call its function. Like:
Doctor doc = new Doctor();
doc.getPatientList();
Else you will have to make the function static.

In the Doctor class, the patientList, loadPatientData() and getPatientList() members are all "instance" members of the class Doctor, which means you need an instance or an object of the type Doctor.
So, to call getPatientList(), you need to create a Doctor object as below:
Doctor doc = new Doctor();
doc.getPatientList();
static members are accessed using the name of the class where as instance members are accessed using the name of the object.

Related

Write JTextField value into ArrayList

Hello i can not write the JTextField's value to the ArrayList in another class the error is "...String can not be converted to Object" how can i fix it?
here is the arraylist class
public class MemberList
{
private ArrayList < Member> members;
/**
* Create a Member.
*/
public MemberList()
{
members = new ArrayList < Member>();
}
/**
* Add a member to this member list.
* #param member the member to be added
*/
public void addMember(Member member)
{
members.add(member);
}
}
and the GUI
public class Test extends JFrame implements ActionListener {
private JTextField jtFName, jtLName, jtMemberNo;
private int nextMemNo;
private MemberList members;
private JFrame frame;
#Override
public void actionPerformed(ActionEvent evt) {
members = new MemberList();
if (evt.getActionCommand().equals("Add Member")) {
if (jtLName.getText().equals("") && (jtFName.getText().equals(""))) {
jtMember.setText("No names");
} else if (jtFName.getText().equals("")) {
jtMember.setText("No first name");
} else if (jtLName.getText().equals("")) {
jtMember.setText("No last name");
} else if (!jtLName.getText().equals("") && (!jtFName.getText().equals(""))) {
btnOne.setText("Confirm");
String fName = jtFName.getText();
String memNo = "1";
String lName = jtLName.getText();
members.addMember(member);
}
} else if (evt.getActionCommand().equals("No. of Members")) {
btnTwo.setText("Clear Number");
jlbMember.setVisible(true);
} else if (evt.getActionCommand().equals("Clear Number")) {
jtFName.setText("");
jtLName.setText("");
} else if (evt.getActionCommand().equals("Quit")) {
System.exit(0);
}
}
}
What do i need to do to add jtFName in the ArrayList?
Sorry for the bad editing and thanks
You have to create a new instance of your Member class and pass it to your addMember method. For example
Member member = new Member(fName, lName); //replace with your actual constructor logic
members.addMember(member);
Your List members contains object of type Member not of type String
Either you make that your List contains String like:
members = new ArrayList<String>();
Or you make a constructor for your Member class in which you pas the String to the object and add the new Object to the List like:
public class Member{
private String name;
public Member(String name){ //create constructor with String argument
this.name = name;
}
}
members.addMember(new Member(name)) //add new Member to list
I can't see your Member class but when I look at your code I think it has a fName, lName and memNo. So in your program the constructor will look like:
public class Member{
private String fName;
private String lName;
private String memNo;
public Member(String fNamen, String lName, String memNo){ //create constructor with String arguments
this.fName= fName;
this.lName= lName;
this.memNo= memNo;
}
}
And add it to the List like:
members.addMember(new Member(fName, lName, memNo));

When is a constructor called in nested classes (Java)

I was trying to understand how constructors work and came up with two questions. I have two classes, one for an address and another for a person. the Person class has two Address objects in it. Here is a simplified example of what I'm doing:
private class Person{
private String name;
private Address unitedStates;
private Address unitedKingdom;
Person()
{
this.name = "lary"
}
Person(String n)
{
this.name = n;
//Can I call Address(string, string) here on unitedStates and unitedKingdom?
}
}//end of person class
private class Address{
private String street;
private String country;
Address()
{
this.street = "1 Washington sq";
this.country = "United States";
}
Address(String s, String c)
{
this.street = s;
this.country = c;
}
}
}
If I leave Person() as is, will it fill the the values for unitedStates and unitedKindom with "1 Washington sq" automatically?
And
Can I pass arguments for the Address object where I left that comment in the example?
Fields of an object will always automatically be set with a default value, if not initialized by yourself. The value depends on the data type of the field (see here https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html). The default value of a field that represents an object is null.
Since you didn't initialize the fields unitedStates and unitedKingdom, their values will be null. What you can do is initializing the fields inside the Person constructors:
Person()
{
this.name = "lary";
this.unitedStates = new Address();
this.unitedKingdom = new Address();
}
Person(String n)
{
this.name = n;
this.unitedStates = new Address("myStreet", "myCountry");
this.unitedKingdom = new Address();
}
You could also use one constructor in another with the keyword this. Note that I have added a third constructor that is called by the other constructors:
Person(String n, Address unitedStates, Address unitedKingdom)
{
this.name = n;
this.unitedStates = unitedStates;
this.unitedKingdom = unitedKingdom;
}
Person(String n)
{
this(n, new Address("myStreet", "myCountry"), new Address());
}
Person()
{
this("lary", new Address(), new Address());
}
Address field are just initialized as null. you have to assign it an Address instance, in User constructor for example, like
unitedStates = new Adress();
wich will call the Address's constructor with no parameters.

Create object for each item in an arraylist

I've been learning java for a little over a month with no previous OOP experience, so please provide simple answers!
The project I'm working on is essentially a simple game. I take a txt file with a variable number of vehicle names, and allow a user to enter a vehicle name followed by a command.
How do I create an object for each item in an arraylist?
This is what I have so far (I put an example of what I'm trying to do in code comments):
public class VehicleApp {
public static void main(String[] args) throws FileNotFoundException, IOException{
File myDir = new File(System.getProperty("user.dir"));
File myFile = new File(myDir, "vehicleNames.txt");
FileReader in = new FileReader(myFile);
BufferedReader br = new BufferedReader(in);
ArrayList<String> vehicleList = new ArrayList<>();
int i = 0;
String line = null;
while((line = br.readLine()) != null){
vehicleList.add(line);
System.out.println(vehicleList.get(i));
//What I'm essentially trying to accomplish:
//Vehicle vehicleList.get(i) = new Vehicle();
i++;
}
br.close();
System.out.println("Enter user input as such:\n" +
"<vehicle name>, <command>");
}
}
I presume you want to actually pass the String to the Vehicle class because it is not possible to dynamically assign a variable name:
Vehicle newVehicle = new Vehicle(vehicleList.get(i));
If you actually meant that you wanted to create a new Vehicle for every item in the ArrayList, you can do that as follows:
for(String s : vehicleList){
Vehicle newVehicle = new Vehicle(s);
}
The above is equivalent to the following:
for(int i=0; i<vehicleList.size(); i++){
Vehicle newVehicle = new Vehicle(vehicleList.get(i));
}
To identify a Vehicle based on the String passed to it, you should use a getter in the Vehicle class as such:
public class Vehicle {
private String name;
public Vehicle(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now you can check if a given Vehicle has a name that matches! For example:
Vehicle vehicle = new Vehicle("Honda Civic");
if(vehicle.getName().equals("Honda Civic")){
System.out.println("Match!");
}
The vehicleList list is of type String. It means that you can only add String objects to that list.
So, you have to change the type of the vehicleList to Vehicle:
ArrayList<Vehicle> vehicleList = new ArrayList<>();
Then, you can create the vehicle objects and pass them in the vehicleList as:
while((line = br.readLine()) != null){
vehicleList.add(new Vehicle(line));
System.out.println(vehicleList.get(i).getName());
}
Remember, you must have a constructor that accepts a name, as well as a storage for that name (member field) as:
private String name;
public Vechicle(String _name)
{
name = _name;
}
in your Vehicle.java class.
In order to print the name of each Vehicle oject using the System.out.println(vehicleList.get(i).getName());,
you have to create a public getter method in your class which retrieves the name of the vehicle:
public String getName()
{
return name;
}
Okay - first things first.
You need a vehicle class.
In a file named Vehicle.java (important)
Make a simple class:
public class Vehicle
{
//vehicle information
private String name;
//Constructors
//default
public Vehicle()
{
name = "";
}
//with param
public Vechicle(String _name)
{
name = _name;
}
}
Now change your array list to contain Vehicle objects
ArrayList<Vehicle> vehicleList = new ArrayList<>();
Then your loop is just
while((line = br.readLine()) != null)
{
vehicleList.add(new Vehicle(line));
}
That should get you started!

java - Editing child in list of parents

I've got an abstract class called customer and another classe called payCust that extends this abstract class. There is another client class that initializes a list of customers.List<Customer> custList = new ArrayList<>();
the customer class has a constructor as follows:
public Customer(String name, String email, String mag) {
this.CusEmail = email;
this.CusName = name;
this.magazine = mag;
}
payCust has the following constructor:
public PayCust(String _name, String _email, String _accountType, String _custMag) {
super(_name, _email, _custMag);
this.accountType = _accountType;
}
all the variables have public get and set methods. e.g.
public void setName(String name) {
this.CusName = name;
}
public String getName() {
return this.CusName;
}
my question is that if the custList had a PayCust added to it. how can i edit the accountType of a customer from that list?
note: email is unique to every customer
You will have to check the instance type of the object within the ArrayList and cast it for usage.
Something like this, for example:
for (Customer c : custList){
if(c instanceof PayCust){
PayCust pc = (PayCust) c;
pc.getAccountType();
}
}
You would have to cast it to a PayCust (assuming you know for a fact that it's a PayCust):
PayCust example = (PayCust) custList.get(0);
String accountType = example.getAccountType ();
...

Setters, why won't this work?

I've been toying for hours, changing static, private, public etcetera :) But it still won't work. If I change static at one place, I get an error at another place etc.
I have a class called person. I've used NON-static Setters because the Person() constructor is also non-static.
public class Person {
private String name;
private String lastname;
private String nickname;
Person() {
this.name = "";
this.lastname = "";
this.nickname = "";
}
public void setName(String name) {
this.name = name;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
}
Then I have a file with my main method, and different methods for interacting with the user.This method is also static because it calls that methods that take the userInput which is using the Scanner class.
public class Interaction {
public static void takeName() {
String name;
String lastname;
String nickname;
System.out.println("What is your firstname:");
name = userInput(); // calls method with Scanner class
System.out.println("What is your lastname:");
lastname = userInput(); // calls method with Scanner class
System.out.println("What is your nickname:");
nickname = userInput();
person.setName(name);
person.setLastname(lastname);
person.setNickname(nickname);
}
//editor: missing closing bracket
What I've tried:
I've tried to dat Person.person.setname(name);
Declare the String in the public class Interaction, and then pass the String using this.name and call the method from the public class Interaction
tried to change static, private etc. etc.
Delete the constructor class Person() in Person class.
What am I missing here?
EDIT: I'VE ADDED SOME MORE INFO as you requested :)
My new Person object will be declared if it passes an if statement.
IF there is a place available then a new person will be created and added to this place.
public class Theater {
void reservationSystem () {
if (availability > 0) {
for (int i = 0; i < freespaces.length; i++) {
if (freespaces[i].person == null) {
freespaces[i].person = new Person();
break;
}
}
} else {
System.out.println("No tickets for you today :) ");
}
}
//editor: missing closing bracket
So my way of thinking is:
I fill a constructor with the data from the Userinput() using the Scanner class;
and THEN I create the new Person object so it has that data!
When I create a new Person in the reservation system, then the data in the constructor will be filled with data AGAIN but now with new data :)
If you need any more information please let me know :)
The first thing to note is that your Person constructor is a little useless, you can rewrite Person as such:
public class Person {
private String name = "";
private String lastname = "";
private String nickname = "";
public void setName(String name) {
this.name = name;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
}
Now onto your Interaction class. This needs to by public rather than Public but I assume that's a typo.
You need to have an instance of Person to call your setters on as they are instance methods. You need to somewhere call new Person().
The easiest way of writing your takeName() method is by creating a Person in the method and returning the instance:
public class Interaction {
public static Person takeName() {
final Person person = new Person();
System.out.println("What is your firstname:");
person.setName(userInput());
System.out.println("What is your lastname:");
person.setLastname(userInput());
System.out.println("What is your nickname:");
person.setNickname(userInput());
return person;
}
}
Your 'takeName()` function should update a single instance of the Person class.
One approach is to create the Person externally and pass it to the function:
Public class Interaction {
public static void takeName(Person person) {
String name;
String lastname;
String nickname;
System.out.println("What is your firstname:");
name = userInput(); // calls method with Scanner class
System.out.println("What is your lastname:");
lastname = userInput(); // calls method with Scanner class
System.out.println("What is your nickname:");
nickname = userInput();
person.setName(name);
person.setLastname(lastname);
person.setNickname(nickname);
}
}
But I think it would be more intuitive to create the person instance inside the function and return it:
Public class Interaction {
public static Person takeName() {
String name;
String lastname;
String nickname;
Person person = new Person();
System.out.println("What is your firstname:");
name = userInput(); // calls method with Scanner class
System.out.println("What is your lastname:");
lastname = userInput(); // calls method with Scanner class
System.out.println("What is your nickname:");
nickname = userInput();
person.setName(name);
person.setLastname(lastname);
person.setNickname(nickname);
return person;
}
}
Because this is not valid syntax: Person.person.setname(name);
What this would mean in this context is:
get class named Person
get static field of Person class named person
find and invoke instance methid setname with argument name
But your Person class - appropriately - does not have a static field named person...
The root cause of your issues is most likely not being entirely familiar with the concept of classes, instances, and in connection, the meaning of static and instance members and methods...
Static always means the referenced part is connected with the class.
Whereas an instance variable or method (e.g. everything non-static) is connected to the instances of said classes.

Categories