// 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.
Related
I have the following 3 classes that is meant to represent a program that allows a user to create a sort of database that can add people and their phone numbers and addresses and then search for them once created.
Here are the classes:
Person
import java.util.*;
public class Person implements Comparable<Person> {
private final String name;
private String street;
private String city;
private String address;
public Person(String name) {
this.name = name;
this.address = "address unknown";
}
public String getName() {
return name;
}
public void setAddress(String street, String city){
this.city = city;
this.street = street;
this.address = this.street + " " + this.city;
}
public String getAddress() {
return address;
}
#Override
public int compareTo(Person o) {
return this.name.compareToIgnoreCase(o.getName());
}
}
PhoneNumbers (to store the person + their phone numbers)
import java.util.*;
import java.util.Collections;
public class PhoneNumbers {
private Map<Person, Set<String>> numbers;
public PhoneNumbers() {
this.numbers = new HashMap<Person, Set<String>>();
}
public void addPhoneNumber(Person person, String phoneNumber){
if(!this.numbers.keySet().contains(person)){
this.numbers.put(person, new HashSet<String>());
}
this.numbers.get(person).add(phoneNumber);
}
public Set<String> searchByPerson(Person person){
if(!this.numbers.keySet().contains(person)){
return this.numbers.get(person);
}
return null;
}
public String searchByNumber(String number){
for(Person person : this.numbers.keySet()){
Set<String> x = this.numbers.get(person);
for(String y : x){
if(y.equals(number)){
return person.getName();
}
}
}
return " not found";
}
public void personalSearch(Person person){
System.out.println(" " + person.getAddress());
if(this.numbers.get(person).size() == 0){
System.out.println(" phone number not found");
}
for(String x : this.numbers.get(person)){
System.out.println(" phone numbers");
System.out.println(" " + x);
}
}
public void remove(Person person){
this.numbers.remove(person);
}
public List<Person> masterSearch(String search){
ArrayList<Person> names = new ArrayList<Person>();
for(Person person : this.numbers.keySet()){
if(person.getName().contains(search) || person.getAddress().contains(search)){
names.add(person);
}
}
Collections.sort(names);
return names;
}
public Map<Person, Set<String>> getNumbers() {
return numbers;
}
}
UI (to provide the way for the user to interact with the program)
import java.util.Scanner;
public class UI {
private Scanner reader;
private PhoneNumbers phoneNumbers;
public UI() {
this.reader = new Scanner(System.in);
this.phoneNumbers = new PhoneNumbers();
}
public void start(){
System.out.println("phone search\n" +
"available operations:\n" +
" 1 add a number\n" +
" 2 search for a number\n" +
" 3 search for a person by phone number\n" +
" 4 add an address\n" +
" 5 search for personal information\n" +
" 6 delete personal information\n" +
" 7 filtered listing\n" +
" x quit\n");
while(true){
System.out.print("command: ");
int command = Integer.parseInt(reader.nextLine());
System.out.println("");
if(command == 1){
System.out.print("whose number: ");
String name = reader.nextLine();
System.out.print("number: ");
String number = reader.nextLine();
Person person = new Person(name);
this.phoneNumbers.addPhoneNumber(person, number);
}
else if(command == 2){
System.out.print("whose number: ");
String person = reader.nextLine();
//something here
}
}
else{
System.out.println(" not found");
}
}
}
}
}
I have a question with the code in the UI specifically
else if(command == 2){
System.out.print("whose number: ");
String person = reader.nextLine();
when the command is given as 2 I ask the user for a name and that is given as a string, how do I then use that String to find the value of the person object with that name under the HashMap i.e. the set of numbers associated with the person.
Obviously I cannot do this with a get method on the map as the keys are person objects not strings and I don't know what to do (do I need to store a map between String name and Person name), I believe in this context names are unique?
Also bonus question: why would I be getting an error when I do command 1 and give a number that is not all digits like "045-4558" for instance.
Thank you
Maybe something like that:
for (Map.Entry<Person, Set<String>> entry : numbers.entrySet()) {
Person key = entry.getKey();
if (key.getName().equals(nameWhichYouAreLookingFor)) {
//Do whatever you want
}
}
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
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.
Basically i am trying to search for specif names in an Array-list and then remove just that name.I am doing an assignment for college, and it species to search and remove by name, so i cant use the int index of, I am fairly new to java, so ill post my code maybe I am missing something any help would be great.
import java.util.ArrayList;
public class GaaClub {
private ArrayList<Member> players;
{
}
public GaaClub() {
players = new ArrayList<Member>();
}
public void addStanderedMember() {
// create a message object:
StdOut.println("Please enter the members's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the members address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the members DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the amount to Pay: ");
double mempaid = StdIn.readDouble();
Member player = new Member(name, address, dob, mempaid);
players.add(player);
}
public void addStandaredPlayer() {
// create a message object:
StdOut.println("Please enter the standard Player's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the standard Player's address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the standard Player's DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the amount to Pay: ");
double mempaid = StdIn.readDouble();
StandardPlayer player = new StandardPlayer(name, address, dob, mempaid);
players.add(player);
}
public void addElitePlayer() {
// create a message object:
StdOut.println("Please enter the Elite Players's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the Elite Players's address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the Elite Players's DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the the amount to Pay: ");
double mempaid = StdIn.readDouble();
StdOut.println("Please enter the Elite Players's BMI: ");
double bmi = StdIn.readDouble();
StdOut.println("Please enter the Elite Players's height: ");
double height = StdIn.readDouble();
ElitePlayer player = new ElitePlayer(name, address, dob, mempaid, bmi,
height);
players.add(player);
}
public static void main(String[] args) {
GaaClub app = new GaaClub();
app.run();
}
public void memberType() {
StdOut.println("Enter Type of membership: ");
StdOut.println("1) Add a Standard Member");
StdOut.println("2) Add an Elite Player");
StdOut.println("3) Add a Standard Player");
String memberchoice = StdIn.readString();
if (memberchoice.equals("1"))
addStanderedMember();
if (memberchoice.equals("2"))
addElitePlayer();
if (memberchoice.equals("3"))
addStandaredPlayer();
}
public void listNames() {
for (Member player : players) {
player.list();
}
}
public void removeName() {
for (Member player : players) {
listNames();
String sResponse = StdIn.readString();
if (sResponse.equals(player.name))
{
players.remove(player);;
return;
}
}
}
private int mainMenu() {
StdOut.println("1) Add a Member");
StdOut.println("2) Remove Player");
StdOut.println("3) List Names");
StdOut.println("4) List Members");
StdOut.println("0) Exit");
StdOut.print("==>>");
int option = StdIn.readInt();
return option;
}
public void run() {
{
StdOut.println("Posts");
int option = mainMenu();
while (option != 0) {
switch (option) {
case 1:
memberType();
break;
case 2:
removeName();
break;
case 3:
addStanderedMember();
break;
case 4:
listNames();
break;
}
option = mainMenu();
}
StdOut.println("Exiting...");
}
}
}
And Second file:
import java.util.ArrayList;
public class Member {
protected String name;
protected String address;
protected String dob;
protected double mempaid;
public Member(String name, String address, String dob, double mempaid) {
this.name = name;
this.address = address;
this.dob = dob;
this.mempaid = mempaid ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDob() {
return dob;
}
public void list(){
System.out.println(name);
}
public void setDob(String dob) {
this.dob = dob;
}
public double getMempaid() {
return mempaid;
}
public void setMempaid(double mempaid) {
this.mempaid = mempaid;
}
#Override
public String toString() {
return "Member [name=" + name + ", address=" + address + ", dob=" + dob
+ ", mempaid=" + mempaid + "]";
}
}
import java.util.ArrayList;
public class StandardPlayer extends Member {
private ArrayList<Competition> competition;
public StandardPlayer(String name, String address, String dob,
double mempaid) {
super(name, address, dob, mempaid);
}
public ArrayList<Competition> getCopmetition() {
return competition;
}
public void setCopmetition(ArrayList<Competition> copmetition) {
this.competition = copmetition;
}
void addCompetiton(Competition c) {
}
void payMembership(double amt) {
mempaid = 0;
}
#Override
public String toString() {
return "StandardPlayer [competition=" + competition + ", name=" + name
+ ", address=" + address + ", dob=" + dob + ", mempaid="
+ mempaid + "]";
}
}
And third file:
import java.util.ArrayList;
public class ElitePlayer extends Member {
private double bmi;
private double height;
private ArrayList<Competition> competition;
public ElitePlayer(String name, String address,
String dob, double mempaid, double bmi, double height) {
super(name, address, dob, mempaid);
this.bmi = bmi;
this.height = height;
}
public double getBmi() {
return bmi;
}
public void setBmi(double bmi) {
this.bmi = bmi;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public ArrayList<Competition> getCopmetition() {
return competition;
}
void payMembership(double amt) {
mempaid = 0;
}
#Override
public String toString() {
return "ElitePlayer [bmi=" + bmi + ", height=" + height
+ ", competition=" + competition + ", name=" + name
+ ", address=" + address + ", dob=" + dob + ", mempaid="
+ mempaid + "]";
}
public void setCompetition(ArrayList<Competition> competition) {
this.competition = competition;`enter code here`
}
}
ArrayList has a method which can remove by Object:
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob");
arr.remove("Bob");
it removes the first instance of the object.
You could of course simulate the same debavior:
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob");
String searchTerm = "Bob";
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).equals(searchTerm) {
arr.remove(i);
break;
}
}
This deviation from the built in method would only be recommended if you wanted to have the search delete on some other, or similar condition. For example if it contained the word "Bob"...
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob Bobingston");
String searchTerm = "Bob";
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).contains(searchTerm)) {
arr.remove(i);
break;
}
}
It seems as if you already have a loop set-up for it. Just loop through the members, check if the name equals what you're looking for, then remove that member from the list if it is
for(Member mem : players) { //loop through each member in list
if(mem.getName().equalsIgnoreCase("name")) { //check if member's name is "name"
players.remove(mem); //removes member from list if it is
}
}
equalsIgnoreCase(String) checks the string without checking for case sensitivity. It won't care for capitalization. If you care about capitalization, use equals(String)
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();
}