Reading in file to array and using it to initialize objects - java

I have 5 classes (they're small). PersonDemo (test class), Person (superclass), and Student, Instructor and Graduate Student (sub classes). All the classes except for PersonDemo are finished.
I need to read in a file (data.txt) and store it to array Person. Then need I need to determine which object to initialize depending on the first value of the array. ( 1 - person, 2 - student, 3 - instructor or 4 - graduate student ) - I'm having trouble with this part.
Can someone point me in the right direction? My classes are below along with what the input file (data.txt) looks like and what the output file should look like.
PersonDemo.Java
public class PersonDemo
{
public static void main ()
{
JFileChooser chooser = new JFileChooser();
Scanner fileScanner = null;
Person [] ins = new Person [10];
try {
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
fileScanner = new Scanner(selectedFile);
while(fileScanner.hasNextLine())
{
// Need to load "data.txt" into array
// Then need I need to determine which object to initialize depending on the
// first value of the array in "data.txt"
//( 1 - person, 2 - student, 3 - instructor or 4 - graduate student )
}
fileScanner.close();
}
}
catch (FileNotFoundException e)
{
System.out.println("Could not find file");
}
}
public static void showAll(Person [] ins)
{
// Future code here
}
}
Person.java (superclass)
public class Person
{
private String name;
private int age;
public Person()
{
name="";
age=0;
}
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String toString()
{
return "Name: " + name + "\t" + "Age: " + age;
}
}
Student.java (subclass)
public class Student extends Person
{
private int studentID;
private String major;
public Student()
{
studentID = 0;
major = "";
}
public Student(String name, int age, int studentID, String major)
{
super(name, age);
this.major = major;
this.studentID = studentID;
}
public int getID()
{
return studentID;
}
public void setID(int studentID)
{
this.studentID = studentID;
}
public String getMajor()
{
return major;
}
public void setMajor(String major)
{
this.major = major;
}
public String toString()
{
return super.toString() + "Student ID: " + studentID + "Major: " + major;
}
}
GraduateStudent.java (subclass)
public class GraduateStudent extends Student
{
private String researchArea;
public GraduateStudent()
{
researchArea = "";
}
public GraduateStudent(String name, int age, int studentID, String major, String researchArea)
{
super(name, age, studentID, major);
this.researchArea = researchArea;
}
public String getArea()
{
return researchArea;
}
public void setArea(String researchArea)
{
this.researchArea = researchArea;
}
public String toString()
{
return super.toString() + "Research Area: " + researchArea;
}
}
Instructor.java (subclass)
public class Instructor extends Person
{
private int salary;
public Instructor()
{
salary = 0;
}
public Instructor(String name, int age, int salary)
{
super(name, age);
this.salary = salary;
}
public int getSalary()
{
return salary;
}
public void setSalary(int salary)
{
this.salary = salary;
}
public String toString()
{
return super.toString() + "Salary: " + salary;
}
}

Related

Generate an ID for each object in java [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 1 year ago.
I have an array in the main class which holds Employee class objects. I'm trying to generate a unique ID for each object but it is printing the same ID for all the objects
Main class:
public static void main(String[] args) {
Employee employee1 = new Employee("Luke", 36);
Employee employee2 = new Employee("Martin", 49);
Employee employee3 = new Employee("Kevin", 21);
Employee employee4 = new Employee("Sam", 43);
Employee employee5 = new Employee("Nicole", 45);
Employee employee6 = new Employee("Linta", 21);
Employee[] allEmployees = { employee1, employee2, employee3, employee4, employee5, employee6 };
for (int i = 0; i < allEmployees.length; i++) {
System.out.println(allEmployees[i]);
}
}
Employee class
public class Employee {
private String name;
private int age;
private static String employeeID = "0";
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = getNextUniqueID();
}
public String getName() {
return name;
}
public String setName(String name) {
this.name =name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static String getNextUniqueID() {
int id = Integer.parseInt(employeeID);
++id;
return Integer.toString(id);
}
public String getEmployeeID() {
return employeeID;
}
public String toString() {
return getName() + " " + getAge() + " " + getEmployeeID();
}
}
I want the employeeID as string and I can't use java.util.UUID; for my project.
You need a static variable associated with the class to maintain the unique id and an instance variable to keep that particular employee's ID in the class.
private String employeeID; // instance member
private static String uniqueID = "0"; // static class variable
public static String getNextUniqueID() {
int id = Integer.parseInt(uniqueID); // get the static variable
++id; // increment it
uniqueID = Integer.toString(id); // update the static variable
return uniqueID; // return the value to use for the employee
}
Then in the Employee constructor, use the static member:
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = Employee.getNextUniqueID();
}
updated Employee class:
public class Employee {
private String name;
private int age;
private String employeeID;
private static String uniqueID = "0";
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = Employee.getNextUniqueID();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static String getNextUniqueID() {
int id = Integer.parseInt(uniqueID);
++id;
uniqueID = Integer.toString(id);
return uniqueID;
}
public String getEmployeeID() {
return employeeID;
}
public String toString() {
return getName() + " " + getAge() + " " + getEmployeeID();
}
}
Output:
Luke 36 1
Martin 49 2
Kevin 21 3
Sam 43 4
Nicole 45 5
Linta 21 6
You should store last generated id in static field but use non static for id of certain employee.
Also you should use AtomicInteger type for thread safety which you can convert to String. Check that:
import java.util.concurrent.atomic.AtomicInteger;
public class Employee {
private String employeeID;
private String name;
private int age;
private static AtomicInteger lastGeneratedId = new AtomicInteger(0);
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = getNextUniqueID();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static String getNextUniqueID() {
return String.valueOf(lastGeneratedId.incrementAndGet());
}
public String getEmployeeID() {
return employeeID;
}
public String toString() {
return getName() + " " + getAge() + " " + getEmployeeID();
}
public static void main(String[] args) {
Employee employee1 = new Employee("Luke", 36);
Employee employee2 = new Employee("Martin", 49);
Employee employee3 = new Employee("Kevin", 21);
Employee employee4 = new Employee("Sam", 43);
Employee employee5 = new Employee("Nicole", 45);
Employee employee6 = new Employee("Linta", 21);
Employee[] allEmployees = { employee1, employee2, employee3, employee4, employee5, employee6 };
for (int i = 0; i < allEmployees.length; i++) {
System.out.println(allEmployees[i]);
}
}
}

Class with an ArrayList inside

I'm new to programming and i'd like some help.
I want to make a class that can add name,age and multiple phone numbers ( in some cases it will be 1, in others 4, etc...) and then show all the info.
I don't want to make it by creating another class for the ArrayList,
I'd like to do it all inside this class, I guess it's something simple to do but I can't figure this out and I'm not finding the solution I want.
what can I do about it? thx in advance, first time posting If I did something wrong please tell me.
import java.util.ArrayList;
public class Athlete
{
private String name;
private int age;
private ArrayList<String> phones = new ArrayList();
public Athlete(String name, int age)
{
this.name = name;
this.age = age;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public ArrayList<String> getPhones()
{
return phones;
}
public void setPhones(ArrayList<String> phones)
{
this.phones = phones;
}
#Override
public String toString()
{
return "Athlete{" + "name=" + name + ", age=" + age + ", phones=" + phones + '}';
}
}
You could make an inner class for PhoneList and use that type instead of directly working with the ArrayList.
public class Athlete
{
private String name;
private int age;
private PhoneList phoneList;
public Athlete(String name, int age)
{
this.name = name;
this.age = age;
phoneList = new PhoneList();
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
// Maybe just return the toString (or a read only list)
public PhoneList getPhones()
{
return phoneList;
}
publicvoid addPhone(String phone)
{
phoneList.add(phone);
}
#Override
public String toString()
{
return "Athlete{" + "name=" + name + ", age=" + age + ", phones=" + phoneList + '}';
}
private class PhoneList
{
private ArrayList<String> list = new ArrayList<String>();
private void add(String phone)
{
list.add(phone);
}
#Override
public String toString()
{
StringBuffer b = new StringBuffer(32);
for (String ph : list)
{
b.append(ph + "\n"); // Or something
}
return b.toString();
}
}
}

Null values when printing out arrayList?

Hi I have created a toStringmethod in one of my classes which can be seen below.
Student Class:
package Practical5;
public class Student extends Person {
//instance variables
private static int MAX_MODULES = 6;
private StudentMode modeOfStudy;
private boolean studentLoan;
private int numEnrolledModules;
//constructor
public Student(String name, String dob, Address address, StudentMode modeOfStudy, boolean studentLoan) {
super(name, dob, address);
this.modeOfStudy = modeOfStudy;
this.studentLoan = studentLoan;
this.numEnrolledModules = 0;
}
//accessors & mutators
public StudentMode getMode() {
return modeOfStudy;
}
public boolean isStudentLoan() {
return studentLoan;
}
public int getNumEnrolledModules() {
return numEnrolledModules;
}
public void setMode(StudentMode modeOfStudy) {
this.modeOfStudy = modeOfStudy;
}
public void setStudentLoan(boolean studentLoan) {
this.studentLoan = studentLoan;
}
public void setNumEnrolledModules(int numEnrolledModules) {
this.numEnrolledModules = numEnrolledModules;
}
#Override
public void purchaseParkingPass() {
System.out.println(getName() + " just purchased a parking pass with student discount.");
}
#Override
public void addModule(String moduleCode) {
if (getNumEnrolledModules() < MAX_MODULES) {
System.out.println(getName() + " successfully registered for the module: " + moduleCode);
}
else {
System.out.println("You are unable to register for " + moduleCode + " as the maximum number of permitted module enrolments has been reached.");
}
}
public String toString() {
return "Student [ ID: " + getId() + "; Name: " + getName() +
"; DOB: " + getDob() + "; Study Mode: " + getMode() +
"; Number of Enrolled Modules: " + getNumEnrolledModules();
}
}
Person Class:
package Practical5;
public abstract class Person {
//instance variables
private static int LAST_ID = 1000 + 1;
private int id;
private String name;
private String dob;
private Address address;
//constructor
public Person(String name, String dob, Address address) {
super();
LAST_ID ++;
this.id = LAST_ID;
}
//accessors & mutators
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getDob() {
return dob;
}
public Address getAddress() {
return address;
}
public void setName(String name) {
this.name = name;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setAddress(Address address) {
this.address = address;
}
//methods
public abstract void purchaseParkingPass();
public abstract void addModule(String moduleCode);
}
I then created a tester class and created a new ArrayList and added these elements to it.
I then created a for loop in order to loop through each element and call the toString method to print out the details of each element but it is returning null values.
Tester Class:
package Practical5;
import java.util.ArrayList;
import java.util.Scanner;
public class UIS_Tester {
public static void main(String[] args) {
Student student1 = new Student("James Black", "07/09/1995" , new Address("Wheeler's Road",10,"Belfast", "BT12 5EG", "Co.Antrim"),StudentMode.Fulltime, false);
Student student2 = new Student("Adam Smith", "12/11/1979" , new Address("Ivy Hill",67,"Belfast", "BT17 7BN", "Co.Antrim"),StudentMode.Parttime, true);
ArrayList<Person> uniPeople = new ArrayList<Person>();
uniPeople.add(student1);
uniPeople.add(student2);
printMenu(uniPeople);
}
public static void printAllDetails(ArrayList<Person> uniPeople) {
for (int i = 0; i < uniPeople.size(); i++) {
System.out.println(uniPeople.get(i).toString());
}
}
}
Output:
Student [ ID: 1002; Name: null; DOB: null; Study Mode: Fulltime; Number of Enrolled Modules: 0
Student [ ID: 1003; Name: null; DOB: null; Study Mode: Parttime; Number of Enrolled Modules: 0
Can anyone help me with this problem? Thanks
public Person(String name, String dob, Address address) {
super();
LAST_ID ++;
this.id = LAST_ID;
}
The constructor completely ignores its three arguments. It doesn't assign them to the corresponding fields, so these fields keep their default value: null.
You have to store the name value in the constructor. Your version did not use the name value.
public Person(String name, String dob, Address address) {
super();
this.name = name; // <== important line
this.dob = dob; // <== important line
this.address = address; // <== important line
LAST_ID ++;
this.id = LAST_ID;
}
Look at the constructor in person and in student, Should use the parameters in the method header.
super(name,dob,address)

How to produce a functional LinkedList Class?

As part of an assignment I am having to produce a LinkedList class called Registry. It is intended to be part of a simple student registration system with an interface.
Unfortately, I have literally hit a wall and have no idea on what to do next with what I am doing here. The Registry class is just intended to manage a linked list of students called studentList.
Below is the current, rather incomplete class I have made so far.
import java.util.*;
public class Registry
{
LinkedList<Student> studentList;
public Registry()
{
}
public void addStudent(Student aStudent)
{
studentList.add(aStudent);
}
public void deleteStudent(int studentID)
{
studentList.remove(studentID);
}
#Override
public String toString()
{
return getClass().getName() +
}
public String format()
{
System.out.format(studentList);
}
}
Now, my main worry is using Student. As part of the assignment, I have had to make another class called Student which create instances of Students, containing forenames, surnames, Student IDs and degree Schemes as strings.
How will I be able to use that sperate class to be added to the LinkedList instanted in Registry? And how can I get the Registry class to fully function?
I will try and provide any additional details on request. I am likely unclear, so if I am, let me know, and I will try and explain as best I can.
EDIT: This is the Student Class as requested:
public class Student
{
private String foreName;
private String surName;
private String studentID;
private String degreeScheme;
public Student()
{
}
public void setForeName(String foreName)
{
this.foreName = foreName;
}
public String getForeName()
{
return foreName;
}
public void setSurName(String surName)
{
this.surName = surName;
}
public String getSurName()
{
return surName;
}
public void setStudentID(String studentID)
{
this.studentID = studentID;
}
public String getStudentID()
{
return studentID;
}
public void setDegreeScheme(String degreeScheme)
{
this.degreeScheme = degreeScheme;
}
public String getDegreeScheme()
{
return degreeScheme;
}
#Override
public String toString()
{
return getClass().getName() + "[foreName = " + foreName + " surName "
+ surName + " studentID " + studentID + " degreeScheme "
+ degreeScheme + "]";
}
public void format()
{
System.out.format("%5s%20s%11s%20s", foreName, surName, studentID, degreeScheme);
}
}
import java.util.Iterator;
import java.util.LinkedList;
public class Tester {
public static void main(String[] args) {
Registry r = new Registry();
r.addStudent(new Student("13", "John", "Doe", "Physics")); // Add a student to the Registry
r.addStudent(new Student("212", "Jane", "Bow", "Chem")); // Add another Student
System.out.println(r); // Print the Student List
r.deleteStudent(212); // Deletes student with ID 212
System.out.println(r);
}
}
class Student {
private String studentID;
private String foreName;
private String surName;
private String degreeScheme;
public Student(String studentId, String foreName, String surName, String degreeScheme) {
this.studentID = studentId;
this.foreName = foreName;
this.surName = surName;
this.degreeScheme = degreeScheme;
}
public void setForeName(String foreName) {
this.foreName = foreName;
}
public String getForeName() {
return foreName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String getSurName() {
return surName;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getStudentID() {
return studentID;
}
public void setDegreeScheme(String degreeScheme) {
this.degreeScheme = degreeScheme;
}
public String getDegreeScheme() {
return degreeScheme;
}
#Override
public String toString() {
return getClass().getName() + "[foreName = " + foreName + " surName " + surName + " studentID "
+ studentID + " degreeScheme " + degreeScheme + "]";
}
public void format() {
System.out.format("%5s%20s%11s%20s", foreName, surName, studentID, degreeScheme);
}
}
class Registry {
LinkedList<Student> studentList;
public Registry() { // Creates studentList
studentList = new LinkedList<>();
}
public void addStudent(Student aStudent) {
studentList.add(aStudent);
}
public void deleteStudent(int studentID) {
int index = searchList(studentID); // Gets index of the student in the Registry
if (index == -1)
throw new IllegalArgumentException("Student not found");
// Since studentList is implemented as LinkedList, .remove removes element at specified position
studentList.remove(index);
}
// Search by studentID , if found, return position in the list
private int searchList(int studentID) {
Iterator<Student> it = studentList.iterator();
int count = -1;
while (it.hasNext()) {
count++;
Student temp;
temp = it.next();
if (Integer.parseInt(temp.getStudentID()) == studentID) {
return count;
}
}
return -1;
}
#Override
//Suggestions to improve the toString are welcome
public String toString() {
for (Student student : studentList) {
student.format();
System.out.println();
}
return "";
}
}
In any data structure there are three functions that almost always require implementation:
Insertion
Searching
Deletion
Let me begin by clarifying what the general Linked List structure consists of.
The linked list works by operating on nodes. Each node contains the actual data you want to store/modify/access.
Registry: This should be responsible for maintaining the structure and providing a way of inserting/searching for/deleting specific nodes in the list.
Student: Stores the data and controls how it is accessed and modified
So far, you have your Registry framework created appropriately. (Although you will want to implement a search method.)
For your student class, you simply create the member variables of the class that you need, as well as the appropriate getters/setters for them.
public class Student {
private String id;
private String forename;
private String surname;
private String degreeScheme;
private Student next; // Maintains a reference to the next node in the list
Student () {
//Default constructor values
}
Student (String id, String forename, String surname, String degreeScheme, Student next) {
this.id = id;
this.forename = forename;
this.surname = surname;
this.degreeScheme = degreeScheme;
this.next = next;
}
public void setID (String id) {
this.id = id;
}
public String getID () {
return id;
}
public void setforename (String forename) {
this.forename = forename;
}
public String getforename () {
return forename;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getSurname () {
return surname;
}
public void setDegreeScheme(String degreeScheme) {
this.degreeScheme = degreeScheme;
}
public String getDegreeScheme () {
return degreeScheme;
}
public void setNext (Student next) {
this.next = next;
}
public Student getNext () {
return next;
}
} //End Student Class
This should be a good base to get you started. Remember, when creating data structures you'll avoid a lot of headaches by making sure that you have a clear separation of concerns. Make the student class purely responsible for storing and maintaining the data, and let the Registry class be responsible for maintaining the structure itself!
At this point, you can utilize the Student class within your Registry class, just insert the nodes as you want, search for them, delete them as needed.

Constructor + Inheritance support

I am fairly new to Inheritance, and I'm not sure if I am doing it right but I seem to be on the right track. The program runs fine except the output I am getting isn't right. I think the problem is to do with my constructors.
public class Person {
protected static String name;
protected static int birthYear;
public Person(String name, int birthYear) {
}
public String name (String n) {
n = name;
return n;
}
public int birthYear (int bY) {
bY = birthYear;
return bY;
}
#Override
public String toString() {
return String.format(name + birthYear);
}
}
public class Student extends Person {
protected String major;
public Student(String name, int birthYear, String major) {
super(name, birthYear);
major = "";
}
public String major(String maj) {
maj = major;
return maj;
}
public String toString() {
super.toString();
return super.toString() + major;
}
}
public class Instructor extends Person {
protected static int salary;
public Instructor(String name, int birthYear, int salary) {
super(name, birthYear);
salary = 0;
}
public int salary(int sal) {
sal = salary;
return sal;
}
public String toString() {
super.toString();
return super.toString() + salary;
}
}
public class PersonTester {
public static void main(String[] args) {
Person p = new Person("Perry", 1959);
Student s = new Student("Sylvia", 1979, "Computer Science");
Instructor e = new Instructor("Edgar", 1969, 65000);
System.out.println(p);
System.out.println("Expected: Person[name=Perry,birthYear=1959]");
System.out.println(s);
System.out.println("Expected:" +
"Student[super=Person[name=Sylvia,birthYear=1979],major=Computer]");
System.out.println(e);
System.out.println("Expected:" + "Instructor[super=Person[name=Edgar,birthYear=1969],salary=65000.0]");
}
}
OUTPUT I AM GETTING:
null0
Expected: Person[name=Perry,birthYear=1959]
null0null
Expected: Student[super=Person[name=Sylvia,birthYear=1979],major=Computer Science]
null00
Expected: Instructor[super=Person[name=Edgar,birthYear=1969],salary=65000.0]
Try changing your constructor in Person to:
public Person(String name, int birthYear) {
this.name = name;
this.birthYear = birthYear;
}
Currently, the constructor has an empty body, so when you call super(name, birthYear); in the subclass constructor, nothing actually happens.
Your Student constructor also has an error. You forgot to initialize the major field.
public Student(String name, int birthYear, String major) {
super(name, birthYear);
this.major = major;
}
You have the same problem in the Instructor constructor...
public Instructor(String name, int birthYear, int salary) {
super(name, birthYear);
this.salary = salary;
}
Finally, you need to take away the static keywords before the fields in Person. This is because static ensures, that there will always be one (and only one) instance of those fields per class, as opposed to one per instance, like you want it to be:
protected String name;
protected int birthYear;
Same thing for the salary field in Instructor.
n = name; this causing your problem. It must be name = n;. All your setter function contain this problem, correct them all and tell me result.

Categories

Resources