ArrayList.remove() is not removing an object - java

I know this is a messy implementation, but I basically have this code (I wrote all of it), and I need to be able to remove a student or instructor from the list when using the appropriate menu choice. Everything else in the code works, just not menu options 3 and 4. I'm entering the exact same information for the object when trying to delete. Here's the code. All three classes are below.
Driver class:
import java.util.ArrayList;
import java.util.Scanner;
public class Driver {
private ArrayList<Student> students;
private ArrayList<Instructor> instructors;
public static void main(String[] args) {
Driver aDriver = new Driver();
aDriver.run();
}
public Driver() {
students = new ArrayList<Student>();
instructors = new ArrayList<Instructor>();
}
private void run() {
Student aStudent;
Instructor anInstructor;
Scanner inp = new Scanner(System.in);
int choice = -1;
String str = "Enter a menu option:\n";
str += " 0: Quit\n";
str += " 1: Add new student\n";
str += " 2: Add new instructor\n";
str += " 3: Delete existing student\n";
str += " 4: Delete existing instructor\n";
str += " 5: Print list of students\n";
str += " 6: Print list of instructors\n";
str += "Your choice: ";
do {
System.out.print(str);
choice = inp.nextInt();
switch(choice) {
case 0:
System.out.println("Thanks! Have a great day!");
break;
case 1:
aStudent = getStudentInfo();
addStudent(aStudent);
break;
case 2:
anInstructor = getInstructorInfo();
addInstructor(anInstructor);
break;
case 3:
aStudent = getStudentInfo();
deleteStudent(aStudent);
break;
case 4:
anInstructor = getInstructorInfo();
deleteInstructor(anInstructor);
break;
case 5:
printStudents();
break;
case 6:
printInstructors();
break;
default:
System.out.println("Invalid menu item " + choice);
}
}
while(choice != 0);
}
public Student getStudentInfo() {
Student aStudent;
String name = null;
String id = null;
double GPA = 0.0;
Scanner inp = new Scanner(System.in);
System.out.print("\n\nEnter the student's name: ");
name = inp.nextLine();
System.out.print("Enter the student's ID: ");
id = inp.nextLine();
System.out.print("Enter the student's GPA: ");
GPA = inp.nextDouble();
aStudent = new Student(name, id, GPA);
return aStudent;
}
public Instructor getInstructorInfo() {
Instructor anInstructor;
String name = null;
String id = null;
String dept = null;
String email = null;
Scanner inp = new Scanner(System.in);
System.out.print("\n\nEnter the instructor's name: ");
name = inp.nextLine();
System.out.print("Enter the instructor's ID: ");
id = inp.nextLine();
System.out.print("Enter the instructor's department: ");
dept = inp.nextLine();
System.out.print("Enter the instructor's email address: ");
email = inp.nextLine();
anInstructor = new Instructor(name, id, dept, email);
return anInstructor;
}
public void addStudent(Student aStudent) {
students.add(aStudent);
}
public void addInstructor(Instructor anInstructor) {
instructors.add(anInstructor);
}
public void deleteStudent(Student aStudent) {
students.remove(aStudent);
}
public void deleteInstructor(Instructor anInstructor) {
instructors.remove(anInstructor);
}
public void printStudents() {
System.out.println("\n\n" + Student.printHeader());
for(int i = 0; i < students.size(); i++) {
System.out.print(students.get(i));
}
System.out.print("\n\n");
}
public void printInstructors() {
System.out.print("\n\n" + Instructor.printHeader());
for(int i = 0; i < instructors.size(); i++) {
System.out.print(instructors.get(i));
}
System.out.print("\n\n");
}
}
Student class:
public class Student {
private String name;
private String id; //String to allow for the possibility of leading zeroes
private double GPA;
public Student() {
name = "TestFirst TestLast";
id = "00000";
GPA = -1.00;
}
public Student(String name1, String id1, double GPA1) {
name = name1;
id = id1;
GPA = GPA1;
}
public static String printHeader() {
String str = String.format("%-25s%-7s%-6s\n", "Name", "ID", "GPA");
return str;
}
public String toString() {
String str = String.format("%-25s%-7s%-6.3f\n", name, id, GPA);
return str;
}
public String getName() {
return name;
}
public void setGPA(double GPA2) {
GPA = GPA2;
}
}
Instructor class:
public class Instructor {
private String name;
private String id;
private String dept;
private String email;
public Instructor() {
name = "TestFirst TestLast";
id = "-00001";
dept = "TestDept";
email = "test#test.net";
}
public Instructor(String name1, String id1, String dept1, String email1) {
name = name1;
id = id1;
dept = dept1;
email = email1;
}
public static String printHeader() {
String str = String.format("%-30s%-6s%-15s%-15s\n", "Name", "ID", "Department", "Email Address");
return str;
}
public String toString() {
String str = String.format("%-30s%-6s%-15s%-15s\n", name, id, dept, email);
return str;
}
public String getName() {
return name;
}
}

You must correctly override the equals() method for both Student and Instructor classes.
When overriding equals, it is good to override hashCode() as well.
new Student(name, id, GPA);
For example, something like this:
public boolean equals(Object o) {
if (!(o instanceof Student)) {
return false;
}
Student other = (Student) o;
return name.equals(other.name) && id.equals(other.id) && GPA == other.GPA;
}
public int hashCode() {
return name.hashCode();
}
This way, you give a chance to the ArrayList figure out which object correspond to the one you passed as a parameter when deleting. If you don't override the above methods, it will use the default implementations in Object, which compare memory addresses which are definitely different as you remove a new Student object.
You can read even more information about the 2 methods in the javadocs for Object.

You need to Override equals and hashcode methods for collections to work properly.
#Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (!(obj instanceof Student))
return false;
Student other = (Student) obj;
return id == null ? false : id.equals(other.id);//Compare Id if null falseF
}
Since you are only using ArrayList there is hashcode method will not be used but it is still good practice to provide it.
#Override
public int hashCode() {
return id == null ? 0 : id.hashCode();
}

You didn't override the method equals for Student and Instructor.
This method is used by the ArrayList to check wether 2 objects are the same. Without a custom implementation it will just check references, which will be different in your case since they are two different objects.
To provide custom equality you will have to check all the fields of the involved classes to be the same. This can be done recursively by calling equals on instance variables.

Overriding the equals method of Student and Instructor will work:
Here is an example for the Student class:
public boolean equals(Object other){
if(other == null) return false;
if(other == this) return true;
if(!(other instanceof Student)) return false;
Student otherStudent = (Student)other;
return otherStudent.id.equals(this.id);
}
You may also want to override hashCode():
public String hashCode(){
return new HashCodeBuilder(17, 31).
append(name).
append(id).
toHashCode();
}

Related

Exception in thread "main" java.lang.NullPointerException when trying to run code in compiler [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
Running into trouble with the output of my code (listed below, separate files and all) where I can execute the correct action up until I need to execute one directly after another. It's spitting out the Exception in thread "main" java.lang.NullPointerException error along with at which lines it is incorrect, however I don't know how to fix it as of now. (This is done in Eclipse compiler)
public class Assignment4
{
public static void main (String[] args)
{
// local variables, can be accessed anywhere from the main method
char input1 = 'Z';
//String inputInfo= "";
String name, firstName, lastName, city ;
int years = 0;
String line = new String();
// instantiate a Team object
Team suns = null;
printMenu();
//Create a Scanner object to read user input
Scanner scan = new Scanner(System.in);
do // will ask for user input
{
System.out.println("What action would you like to perform?");
line = scan.nextLine();
if (line.length() == 1)
{
input1 = line.charAt(0);
input1 = Character.toUpperCase(input1);
// matches one of the case statement
switch (input1)
{
case 'A': //Add a coach
System.out.print("Please enter the Coach's information:\n");
System.out.print("Enter coach's first name:\t");
firstName = scan.nextLine();
System.out.print("Enter coach's last name:\t");
lastName = scan.nextLine();
System.out.print("Enter coach's years of experience:\t");
years = scan.nextInt();
scan.nextLine();
Coach sunsCoach = new Coach(firstName, lastName, years);
System.out.print("\nPlease enter the Team's information:");
System.out.print("\nEnter teams name:\t");
name = scan.nextLine();
System.out.print("Enter Team's city:\t");
city = scan.nextLine();
suns = new Team(name, sunsCoach, city);
break;
case 'D': //Display course
System.out.print(suns.toString());
break;
case 'Q': //Quit
break;
case '?': //Display Menu
printMenu();
break;
default:
System.out.print("Unknown action\n");
break;
}
}
else
{
System.out.print("Unknown action\n");
}
} while (input1 != 'Q' || line.length() != 1);
scan.close();
}
/** The method printMenu displays the menu to a user **/
public static void printMenu()
{
System.out.print("Choice\t\tAction\n" +
"------\t\t------\n" +
"A\t\tAdd Coach\n" +
"D\t\tDisplay Team\n" +
"Q\t\tQuit\n" +
"?\t\tDisplay Help\n\n");
}
}
Along with this code, there are my two child class files, Coach.java and Team.java respectively, listed below.
public class Coach
{ String firstName, lastName; //constructor
int years;
{ String numYears;
firstName = lastName = numYears = "?";
}
public Coach(String first, String last, int years) { //Set variables
firstName = first;
lastName = last;
int numYears = years;
}
//Accessors
public String getFirstName()
{return firstName;}
public String getLastName()
{return lastName;}
public String getYears()
{String numYears = null;
return numYears;}
// Mutators
public void setFirstName(String theFirstName)
{firstName = theFirstName;}
public void setLastName(String theLastName)
{lastName = theLastName;}
public void setYears(int years)
{int numYears = years;}
public String toString() {
String output = "\nLast Name:\t" + lastName + "\nFirst Name:\t " + firstName;
output += "\nYears of Experience:\t " + getYears() + "\n";
return output;
}
}
public class Team {
String teamName;
Coach coach;
String getCity;
//Constructor
public Team() {
teamName = getCity = "?";
}
public Team(String name, Coach coach, String cityName)
{ teamName = name;
}
//Accessors
public String getName() {return teamName;}
public Coach getCoach() {return coach;}
public String getCity() {return getCity;}
//Mutators
public void setName(String theName) {teamName = theName;}
public void setCity(String someCity) {getCity = someCity;}
public void setCoach(String firstName, String lastName, int years)
{ coach = new Coach (firstName, lastName, years);
}
public String toString()
{ String output = "Team's name:\t" + teamName + " at " + getCity() + "\nCoach Information:";
output += coach.toString();
return output;
}
}
Running the code, and putting in inputs until I wish to select option D, will eventually yield this specific error:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Coach.toString()" because "this.coach" is null
at Team.toString(Team.java:30)
at Assignment4.main(Assignment4.java:68)
suns = new Team(name, sunsCoach, city);
As I can see you are passing sunsCoach as a parameter to the constructor of Team, but you are not initialising the coach object.
Update your code from
public Team(String name, Coach coach, String cityName)
{
teamName = name;
}
to
public Team(String name, Coach coach, String cityName)
{
teamName = name;
coach = coach;
getCity = cityName;
}
this would resolve the NullPointerException

Find max value from an object [duplicate]

This question already has answers here:
Getting max value from an arraylist of objects?
(5 answers)
Closed 2 years ago.
I have super class Person that extends to 2 sup classes (Employee and Student), after I enter the Employee info such as (name, SSN, salary, Gendr) I want to find the Employee with the Max salary and type his\her info, but I don't know how to do that with objects !, if u may please give me a hint I'll be thankfull.
public abstract class Person {
private String name=" ";
private String gender=" ";
private long SSN;
public Person() {
}
public Person(String name, String gender, long SSN) {
this.name = name;
this.gender = gender;
this.SSN = SSN;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public long getSSN() {
return SSN;
}
public void setSSN(long SSN) {
this.SSN = SSN;
}
#Override
public String toString() {
return name + " " + gender + " " + SSN+ " ";
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Person other = (Person) obj;
if (this.SSN != other.SSN) {
return false;
}
if (!Objects.equals(this.gender, other.gender)) {
return false;
}
return true;
}
}
public class Employee extends Person {
private String type = " ";
private double salary;
public Employee() {
}
public Employee(double salary, String name, String gender, long SSN) {
super(name, gender, SSN);
this.salary = salary;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return super.toString()+ " " + type + " " + salary ;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Employee other = (Employee) obj;
if (Double.doubleToLongBits(this.salary) != Double.doubleToLongBits(other.salary)) {
return false;
}
if (!Objects.equals(this.type, other.type)) {
return false;
}
return true;
}
}
public class Test {
static void print(Person[] all, int count){
System.out.println("The allPersons array contains: ");
for (int i = 0; i <count; i++) {
System.out.println(all[i]);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Person[] allPersons = new Person[5];
String name = " ";
long ssn=0;
String gender = " ";
int count = 0;
boolean s = true;
while(s){
System.out.println("Choose 1 to insert a new student");
System.out.println("Choose 2 to insert new employee");
System.out.println("Choose 3 to retrieve the maximum salary");
System.out.println("Choose 4 to retrieve all software engineering students");
System.out.println("Choose 0 to exit");
System.out.println("Please enter your choice: ");
int n = input.nextInt();
switch(n){
case 1:{ if(count == 5){System.out.println("Sorry, you reach the maximum length."); break;}
Student student = new Student();
System.out.println("Please enter Name: ");
name=input.next();
input.nextLine();
student.setName(name);
System.out.println("Please enter SSN: ");
ssn = input.nextLong();
student.setSSN(ssn);
System.out.println("Plase enter Gender: " );
gender = input.next();
student.setGender(gender);
System.out.println("Please enter major: ");
String major = input.next();
input.nextLine();
student.setMajor(major);
System.out.println("Plase inter Year of Regestration: ");
int year = input.nextInt();
student.setYearOfReg(year);
System.out.println("Please enter Studend ID: ");
long ID = input.nextLong();
student.setID(ID);
allPersons[count]=student;
count++;
print(allPersons,count);}
case 2 :{if (count==5) {System.out.println("Sorry, you reach the maximum length"); break;}
Employee emp = new Employee();
System.out.println("Please enter Name:");
name=input.next();
input.nextLine();
emp.setName(name);
System.out.println("Plese enter SSN:");
ssn=input.nextLong();
emp.setSSN(ssn);
System.out.println("Please enter Gender:");
gender=input.next();
emp.setGender(gender);
System.out.println("Plese enter type: ");
String type = input.next();
input.nextLine();
emp.setType(type);
System.out.println("Please enter Salary:");
double salary = input.nextDouble();
emp.setSalary(salary);
allPersons[count]=emp;
count++;
print(allPersons,count);
}
case 3: //Employee with max salary
case 0: System.out.println("Exit");s=false;break;
}
}
}
}
You can loop over the array of people and find the employee with the highest salary.
Employee highest = null;
for(int i = 0; i < count; i++){
if(allPersons[i] instanceof Employee && (highest == null || ((Employee) allPersons[i]).getSalary() > highest.getSalary())){
highest = (Employee) allPersons[i];
}
}
System.out.println(highest);
You can use a lambda function to obtain the max salary and check the type of person in the same function.
public Employee getMaxSalary(Person[] allPersons) {
return Arrays.asList(allPersons)
.stream()
.filter(Employee.class::isInstance) //Filter only the person who are Employee
.map(Employee.class::cast)
.max(Comparator.comparing(Employee::getSalary)) //Obtain only the max salary
.orElseThrow(NoSuchElementException::new);
}

How to create an arraylist using polymorphism?

I am trying to create an array list that contains all employees and is able to handle any type of employee. I also have to load the data onto to the list The class I'm using is called payroll. This is what I have so far:
The employee class looks like this:
import java.util.*;
public abstract class Employee
{
private String name, employeeNum, department;
private char type;
public Employee()
{
name ="";
employeeNum = "";
department = "";
}
public Employee(String Name, String EmpNum, String Depart)
{
name = Name;
employeeNum = EmpNum;
department = Depart;
}
//public EMpoy
public String getName()
{
return name;
}
public String getEmployeeNum()
{
return employeeNum;
}
public String getDepartment()
{
return department;
}
public char getType()
{
return type;
}
public void setName(String Name)
{
name = Name;
}
public void setEmployeeNum(String EmpNum)
{
employeeNum = EmpNum;
}
public void setDepartment(String Depart)
{
department = Depart;
}
public String toString()
{
String str;
str = "Employee Name: " + name + "\n"
+ "Employee Number: " + employeeNum + "\n"
+ "Employee Department: " + department + "\n";
return str;
}
}
The payroll class looks like this so far:
import java.util.*;
import java.io.*;
public class Payroll
{
private ArrayList<Employee> list = new ArrayList<Employee>();
private String fileName;
public Payroll()
{
}
public void fileName(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("InsertFileName");
String fileName1 = kb.next();
fileName = fileName1 + ".txt";
}
public void loadData() throws FileNotFoundException
{
Scanner s = new Scanner(new File(fileName));
while (s.hasNext())
{
String name = s.next();
String employeeNum = s.next();
String department = s.next();
//String typeString = s.next();
//char type = typeString.toUpperCase().charAt(0);
char type = s.next().toUpperCase().charAt(0);
if (type == 'S')
{
double yearlySalary = s.nextDouble();
list.add(new Salary (name, employeeNum, department, yearlySalary));
}
else if (type == 'H')
{
double hourlyPayRate = s.nextDouble();
String hours = s.next();
int hoursWorked = Integer.parseInt(hours);
list.add(new Hourly (name, employeeNum, department, hourlyPayRate, hoursWorked));
}
else if (type == 'C')
{
int numOfWeeks = s.nextInt();
double baseWeeklySalary = s.nextDouble();
int salesThisWeek = s.nextInt();
int salesThisYear = s.nextInt();
double commissionRate = s.nextDouble();
list.add(new Commission (name, employeeNum, department, numOfWeeks, baseWeeklySalary, salesThisWeek, salesThisYear, commissionRate));
}
}
s.close();
}
Now I know I'm supposed to make the arraylist in the constructor, that's what I'm having trouble with. How can I make the list using polymorphism to get every employee? Thanks.
Hi Srk93 You are getting error as your list contains the references of Employee class and Employee class does't have getCommissionRate method. You can call on Employee reference which are declared in Employee class. Create abstact method of calculateSalary() and implement in all your child classes.
Its duplicate of "cannot find symbol: method" but the method is declared

Getting NullPointerException errors when trying to use multiple classes for the first time

I am trying to get my addStudent() method in the Roster class to work here.
It's supposed to add a given student to this roster. If the student is already on the roster, or the numStudents == stopPoint, it doesn't change the roster and returns false. If it is successful it returns true.
Roster Class:
public class Roster {
Student[] students;
int numStudents;
int stopPoint;
Course course;
//constructor for this class initialize this roster to empty
public Roster(int stopPoint, Course course)
{
this.stopPoint = stopPoint;
this.course = course;
}
//returns a string that represents the object for printing
public String toString()
{
String res = "";
for(int j = 0; j < numStudents; j++)
{
res = res + "\n" + students[j].toString();
}
return course + " " + numStudents + "/" + stopPoint+res;
}
//returns true if and only if the number of students in it is at stopPoint
public boolean isFull(int numStudents, int stopPoint)
{
if (numStudents == stopPoint)
{
return true;
}
else
return false;
}
/*add given student to this roster if student already on roster
or numStudents already == stopPoint, will not change roster and return
false but return true if successful, else false
*/
public boolean addStudent(Student student)
{
if(this.numStudents < this.stopPoint)
{
this.students[numStudents] = student; // here is where I get the error
this.numStudents++;
return true;
}
else
return false;
}
}
Testing Class:
public class TestRoster
{
public static void main(String[] args)
{
Student s1 = new Student("John","Doe");
Course c1 = new Course(198, 111);
Roster r1 = new Roster(4, c1);
System.out.println(r1);
testAdd(r1, s1);
}
private static void testAdd(Roster r, Student s)
{
System.out.println(s.familyName+" "+r.addStudent(s));
System.out.println(r);
}
}
Student Class:
public class Student
{
String personalName;
String familyName;
public Student(String pName, String fName)
{
personalName = pName;
familyName = fName;
}
public String toString( )
{
return "Student: " + familyName + ", "+ personalName;
}
}
Lastly, the Course Class:
public class Course
{
int deptNum;
int courseNum;
public Course(int deptNum, int courseNum)
{
this.deptNum = deptNum;
this.courseNum = courseNum;
}
public String toString( )
{
return deptNum + ":" + courseNum;
}
}
Here is the error:
Exception in thread "main" java.lang.NullPointerException
at assign4.Roster.addStudent(Roster.java:56)
at assign4.TestRoster.testAdd(TestRoster.java:17)
at assign4.TestRoster.main(TestRoster.java:13)
Java Result: 1`
The other answers suggest using an arbitrary number for the array instansiation, this is not a good idea as you never know if it will be enough.
Your Roster class knows how many students there should be (via the constructor), you should initialize the Student array with stopPoint:
Student[] students;
int numStudents;
int stopPoint;
Course course;
public Roster(int stopPoint, Course course)
{
this.stopPoint = stopPoint;
this.course = course;
this.students = new Student[this.stopPoint]
}
Since you can't touch your class variables, you can and should initialize the array within the constructor.

Getting an Exception in thread main error on my Faculty Class

// to create address object, and pass the address to faculty
// Must connect to other classes simultaneously
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Driver {
public static ArrayList<Student> student = new ArrayList<Student>();
public static ArrayList<Course> course = new ArrayList<Course>();
public static ArrayList<FacultyMember> faculty = new ArrayList<FacultyMember>();
public static void main(String[] args) {
String[] choices = { "0 Exit", "1 Add Student", "2 List of Students",
"3 Remove Student", "4 Create course", "5 List of Courses",
"6 Remove Course", "7 add instructor", "8 List of Instructors",
"9 Remove Instructor" };
student.add(new Student(308765433, "phillip", 2436, "Daly Street",
"Los Angeles", "CA", "USA"));
student.add(new Student(308765434, "Wilson Lucey", 2436,
"Broadway Street", "Los Angeles", "CA", "USA"));
student.add(new Student(308765432, "William", 2436,
"University Street", "Los Angeles", "CA", "USA"));
course.add(new Course(23545, "CS201"));
course.add(new Course(23546, "CS202"));
course.add(new Course(23547, "CS203"));
faculty.add(new FacultyMember(23477, "John"));
// faculty.add(new FacultyMember(23587, "Keenan"));
// faculty.add(new FacultyMember(236, "Parviz"));
int a = -1;
while (a < 0) {
int choice = JOptionPane.showOptionDialog(null, "Welcome", "Menu",
a, a, null, choices, a);
if (choice == 0) {
System.exit(0);
}
if (choice == 1) { // DONE
addStudent();
}
if (choice == 2) { // List all students inside array of students.
String a1 = "";
for (Student b : student) {
// b.toString();
a1 = a1 + b.toString() + "\n";
}
JOptionPane.showMessageDialog(null, a1);
}
if (choice == 3) {
removeStudent();
}
if (choice == 4) { // Show all courses inside array of courses
addCourse();
}
if (choice == 5) { // List of Course
String c1 = "";
for (Course b : course) {
// b.toString();
c1 = c1 + b.toString() + "\n";
}
JOptionPane.showMessageDialog(null, c1);
}
if (choice == 6) {
removeCourse();
}
if (choice == 7) {
addFaculty();
}
if (choice == 8) { // LIST OF FACULTY
String d1 = "";
for (FacultyMember d : faculty) {
// b.toString();
d1 = d1 + d.toString() + "\n";
}
JOptionPane.showMessageDialog(null, d1);
}
if (choice == 9) { // REMOVE FACULTY
removeFaculty();
}
}
}
private static void addStudent() {
int CIN = Integer.parseInt(JOptionPane.showInputDialog("Enter CIN: "));
String Name = JOptionPane.showInputDialog("Enter name");
// int street, String name, String city, String state, String country
int Street = Integer.parseInt(JOptionPane
.showInputDialog("Enter street #"));
String StreetName = JOptionPane.showInputDialog("Enter Street Name");
String City = JOptionPane.showInputDialog("Enter city");
String State = JOptionPane.showInputDialog("Enter state");
String Country = JOptionPane.showInputDialog("Enter country");
Student s1 = new Student(CIN, Name, Street, StreetName, City, State,
Country);
student.add(s1);
}
private static void addCourse() { // If
int courseID = Integer.parseInt(JOptionPane
.showInputDialog("Enter the id numer please!"));
String courseTitle = JOptionPane
.showInputDialog("Enter a course please!");
// String instructorName = JOptionPane
// .showInputDialog("Enter instructor for the course please!");
Course c1 = new Course(courseID, courseTitle); // CREATE OBJECT
course.add(c1);
}
// private static void Course(int courseID, String courseTitle, String term,
// String instructorName) {
//
// }
private static void addFaculty() {
int employeeID = Integer.parseInt(JOptionPane
.showInputDialog("Enter the employee id numer please!"));
String facultyName = JOptionPane
.showInputDialog("Enter the name of faculty please!"); // SAME
// AS
// STUDENTS
FacultyMember f1 = new FacultyMember(employeeID, facultyName);
faculty.add(f1);
}
public static void removeStudent() {
String a1 = "";
int i = 0;
for (Student b : student) {
// b.toString();
a1 = a1 + i++ + b.toString() + "\n";
}
int LineNumber = Integer.parseInt(JOptionPane.showInputDialog(null, a1
+ "Enter a row # to remove, please"));
student.remove(LineNumber);
for (int k = 0; k < student.size(); k++) {
System.out.println(student.get(k));
}
}
public static void removeCourse() {
String a1 = "";
int i = 0;
for (Course b : course) {
// b.toString();
a1 = a1 + i++ + b.toString() + "\n";
}
int LineNumber = Integer.parseInt(JOptionPane.showInputDialog(null, a1
+ "Enter a row # to remove, please"));
course.remove(LineNumber);
for (int k = 0; k < course.size(); k++) {
System.out.println(course.get(k));
}
}
public static void removeFaculty() {
String b1 = "";
int i = 0;
for (FacultyMember b : faculty) {
// b.toString();
b1 = b1 + i++ + b.toString() + "\n";
}
// JOptionPane.showMessageDialog(null,
// a1+"Enter a row # to remove, please");
//
int LineNumber = Integer.parseInt(JOptionPane.showInputDialog(null, b1
+ "Enter a row # to remove, please"));
faculty.remove(LineNumber);
for (int k = 0; k < faculty.size(); k++) {
System.out.println(faculty.get(k));
}
}
}
// }
public class Address {
/*
* An address has a street number, street name, city, state or province, and
* country.
*/
private int street;
private String name;
private String city;
private String state;
private String country;
public Address(int street, String name, String city, String state, String country) {
this.street = street;
this.name = name;
this.city= city;
this.state = state;
this.country = country;
}
public int getStreet() {
return street;
}
public void setStreet(int street) {
this.street = street;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity(String city){
return city;
}
public void setCity(String city){
this.city=city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String toString() {
return name + " "+
"Street: "+street+ " "+
"City: "+city+ " , "+ " State: "+ state +
"Country: "+country;
}
}
public class Person {
/*
* A Person has a name and an Address (represented by an object of class
* Address, not a String). Note that the subclasses of Person inherit the
* fields and methods of Person. You may need to override some of the
* methods in the subclasses.
*/
protected String name;
protected Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setAddress(int street, String name, String city, String state,
String country) {
Address set1 = new Address(street, name, city, state, country);
this.address = set1;
}
public String toString() {
return "Name: " + name + " "+"Address: " + address.toString();
}
}
public class Course {
private int identifier;
private String courseTitle;
public Course(int identifier, String courseTitle){
this.identifier= identifier;
this.courseTitle= courseTitle;
}
public int getIdentifier() {
return identifier;
}
public String getCourseTitle() {
return courseTitle;
}
public String toString(){
return "Course ID: "+identifier + "Course title: "+ courseTitle;
}
public boolean contains(Course course) {
// TODO Auto-generated method stub
return false;
}
//setter to change the object values
//getters is to return some values we need
}
import java.util.ArrayList;
import java.util.List;
public class FacultyMember extends Person{
private int employeeID;
public ArrayList<Course>course = new ArrayList<Course>();
public FacultyMember(int employeeID, String nameIn){
this.name= nameIn;
this.employeeID = employeeID;
}
public int getID(){
return employeeID;
}
public void setID(int employeeID){
this.employeeID = employeeID;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public List<Course> getCourse(){
return course;
}
public void addCourse(Course course) {
this.course.add(course);
}
public String toString(){
return "EmployeeID: " + employeeID +super.toString() ;
}
}
Write a Driver class that maintains lists of Students, Courses, and
FacultyMembers and has a menu that provides ways to list, create, and delete
them based on user input. The driver class should also provide a way for a
student to add and drop existing Courses and a way to assign faculty member
to teach existing Courses. Do not create a new Course when a Student adds or
when a faculty member is assigned to teach; let the user choose a Course from
the list. Think about how to organize this input before you start coding.
Include a method that can be called from main that will use your methods to
add and delete some hard-coded test data (several students, several faculty
members, and several courses.) This will let you code the lists and test the
methods to add and delete items without using the user input functions.
I am having difficulty with my Faculty Member class I am getting this error
Exception in thread "main" java.lang.NullPointerException
at Person.toString(Person.java:30)
at FacultyMember.toString(FacultyMember.java:33)
at Driver.main(Driver.java:83)
As said earlier, you are calling toString on the address instance variable in your Person class, but you never instantiate the variable, meaning it has the default value for an Object: null.
If you try to call a member of a non instantiated variable, it will throw a NullPointerException.
public String toString() {
return "Name: " + name + " "+"Address: " + address.toString();
}
Either remove the toString call for address, or make sure you instantiate it.
That being said, there is much that can be improved on your code:
code like this:
if (choice == 6) {
removeCourse();
}
if (choice == 7) {
addFaculty();
}
if (choice == 8) { // LIST OF FACULTY
String d1 = "";
for (FacultyMember d : faculty) {
// b.toString();
d1 = d1 + d.toString() + "\n";
}
JOptionPane.showMessageDialog(null, d1);
}
if (choice == 9) { // REMOVE FACULTY
removeFaculty();
}
is not efficiƫnt. I think we can both agree, that if choice == 6, choice will never (at the same time) have the value7, 8 or 9, yet you still test for them.
One way to improve this, is using else statements:
if (choice == 6) {
removeCourse();
}else if (choice == 7) {
addFaculty();
} else if (choice == 8) { // LIST OF FACULTY
String d1 = "";
for (FacultyMember d : faculty) {
// b.toString();
d1 = d1 + d.toString() + "\n";
}
JOptionPane.showMessageDialog(null, d1);
}else if (choice == 9) { // REMOVE FACULTY
removeFaculty();
}
When you do this, it will not check if choice has one of the values, if it already found the value it has in a previous test. So, if choice == 6, it will not test for 7, 8 or 9.
Even though this is a lot better, it 's still not very easy to read. a switch statement can help here:
switch(choice){
case 6: removeCourse();
break;
case 7: addFaculty();
break;
case 8: String d1 = "";
for (FacultyMember d : faculty) {
// b.toString();
d1 = d1 + d.toString() + "\n";}
JOptionPane.showMessageDialog(null, d1);
break;
case 9: removeFaculty();
break;
}
Add proper indentation to that, and you'll have a lot easier to maintain code.
No doubt there is more you can improve, but this 'll give you something to start with.

Categories