Create object for each item in an arraylist - java

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!

Related

What Pattern design to get rid of the type casting in my case?

public abstract class Employee {
String name;
String position
public Employee(String name, String position) {
this.name = name;
this.position = position
}
}
public class Pilot extends Employee {
public Pilot(String name,String position) {
super();
}
public void flight() {//flight the plane}
//getter and setter for the fields
}
public class Attendance extends Employee {
public Attendance(String name,String position) {
super();
}
public Food servingFood(String foodName) {}
}
// there will be many other positions
public class Company {
HashMap<String, ArrayList<Employee>> employeeTable; //values is a list of workers, key is the position
public Company() {this.employeeTable = new HashMap<>();}
public initializeEmployeeTable(file) {} //read file, and create keys in map (file contains information of the position)
public Worker hireEmployee(String position, String name){
if (position.equals("pilot")) {
Pilot p = Pilot(name);
employeeTable.get("pilot").add(p);
return p
}
else if (position.equals("flightAttendance")) {// the else if statement continuous to check the other position; }
}
public Worker callEmployee(String position, String name) {
for ( Employee e : employeeTable.get(position) ) {
if e.getName().equals(name) {
return e;
}
}
return null;
}
public static void main(String[] args) {
Company company = new Company();
company.initializeEmployeeTable(filePath);
File eventFile = new File(filePath); // event file describes what's happening in real world; read the lines, and call the program so that program simulates the real world events
sc = new Scanner(eventFile);
do {
String currentEvent = sc.nextLine();
String[] currentEventParts = currentEvent.split(", ");
if (currentEvent[0].equals("New Airplane")) { // currentEvent looks like {"New Airplane", "Attendance"// this part can be other position name, "Linda"}
Worker w = company.hireEmployee(currentEventParts[1], currentEventParts[2]); }
else if ((currentEvent[0].equals("flying"))) {
Worker w = company.callEmployee(currentEvent[0], currentEvent[1])
if (w.getPosition().equals("Pilot")) {(Worker) w.flight()}
if (w.getPosition().equals("Attendance")) {(Worker) w.serveFood()}
}
}
The reason there is HashMap for employee because there will be many positions; and reading the event file (when the first index is "New Airplane"); I don't want to go check the following index (would be name and position) with so many if statements to create corresponding employee. But when comes to calling specific methods, I need type casting now; since each method can be different (different type parameter, return type); so it's not ideal to have this methods be abstract method in super class employee and have the subclass implements the body.
Any advices: employee data structure; reading file strategy, pattern design would be appreciated. thanks

Convert String to object in java

I have a HashSet in where I need to store the available ingredients.
HashSet<Ingredient> availableIngreds = new HashSet<>();
The available ingredients are read from a file.
Scanner file = new Scanner(new File(fileName));
while (file.hasNext()) {
availableIngreds.add(file.next()); //Non working code
}
System.out.println("*** Available ingredients ***");
for (Ingredient i : availableIngreds) {
System.out.println(i);
}
My problem is that the file contains the ingredients as strings (flour, sugar, milk etc).
My HashSet needs to store the ingredients as object of the class Ingredient.
How can I convert String to Ingredient so the above line of code works?
Thank you for your help.
* edit *
class Ingredient:
public class Ingredient {
private String iName;
public Ingredient(String aName) {
iName = aName;
}
public String getName() {
return iName;
}
public String toString() {
return iName;
}
public boolean equals(Object rhs) {
return iName.equals(((Ingredient)rhs).iName);
}
public int hashCode() {
return iName.hashCode();
}
}
You already have a constructor for Ingredient that accepts a String. Just use it when adding values to your HashSet:
while (file.hasNext()) {
availableIngreds.add(new Ingredient(file.next()));
}
Since file.next() returns a String, and you need to create in Ingredient object from it, overload the constructors with one that take a String as a parameter (I'm assuming that your Ingredient class has a String field in which you store the actual ingredient name), create the Ingredient object you want with it and then store it in your Hashmap.

Static Suggestion. What am I doing wrong?

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.

Initialize each element of the array with Student objects

public class Student {
int marks;
String name;
char sex;
String email;
}
Student[] s = new Student[10];
public class StudentDemo {
Student s[] = new Student[10];// array Student//
Student s1 = new Student();// Student Object//
s1.setName("John"); //Eclipse says here there is a mistake an ask to delete John//
Student[0]=s1;
}
I have created a Student class with name and other attributes. But now I want to initialize each element of the array with Student objects. Is this code right? Eclipse throws a lot of red dots.
Help.
class Student {
int marks;
String name;
char sex;
String email;
public void setName(String string)
{
// TODO Auto-generated method stub
}
}
public class StudentDemo{
public static void main(String [] args)
{
Student s[] = new Student[10];// array Student//
Student s1 = new Student();// Student Object//
s1.setName("John"); //Eclipse says here there is a mistake an ask to delete John//
s[0]=s1;
}
}
Try this.
Problems in your code:
You wrote your function logic outside of function. Corrected in my
code using main method.
You can't have 2 public classes in a class file. So i made Student file as non-public.
You din't have setter for name property of Student.
Well you never defined a setName method so I am assuming thats why you got the compiler error. Something like this should work inside the Student class
public String setName(String name){
this.name = name;
}
use the reference of the array you created instead of the type of array
Thus, replace Student[0] with s[0]
A lot is wrong with your code.
It should be
Student[] s = new Student[10];
s[0] = new Student();
s[0].setName();
You need to also write your code inside a method. Like so:
public void doStuffHere()
{
// Code goes here.
}
Notice I use that fact that at position 0 there is a Student object and then I just set the name. There is no real reason to use s1.
A few things:
First of all, your first array should be written like this:
Student[] s = new Student[10];
Secondly, you never defined the method setName(String name) in your Student class. This would look something like this:
public void setName(String name)
{
this.name = name;
}
On top of that, you can't just call the method in the class, it needs to go inside a method, constructor, or initialisation block.
For example:
public class StudentDemo
{
Student[] studentArray = initStudentArray();
private Student[] initStudentArray()
{
Student[] ret = new Student[10];
Student s = new Student();
s.setName("John");
ret[0] = s;
...
return ret;
}
}
This can help you.
class Student {
int marks;
String name;
char sex;
String email;
void setName(String name){
this.name = name; //this.name represents the current instance non-static variable
}
public String toString(){ //Overridden Objectclass method for string representation of data
return " Student Name: "+name+
"\n Gender: "+sex+
"\n Email: "+email+
"\n Marks: "+marks;
}
}
public class StudentDemo {
public static void main(String[] args){
Student s[] = new Student[10];
s[0] = new Student();
s[0].setName("John"); //similarly u can set values to other attributes of this object
System.out.println(s[0]); // same as s[0].toString() its an implicit call
}
}

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 ();
...

Categories