Having trouble removing a specific element from a linked list - java

I have been set an assignment to create a small register based program written in Java, in the form of a linked list. I started by creating a student class, and then a tester file for the class. Following that, in the registry file I have set out my methods, and a constructor, and am in the process of writing a tester file to test all my methods.
However I am having trouble when trying to remove a specific element from my linkedlist, I want to be able to remove a student, referencing them by their individual studentID, but am not sure how to do this.
Whilst trying to solve the problem I came across the removeFirstOccurrence(Object o) method. Is this the right method to use?
Any help would be much appreciated.
STUDENT FILE CODE:
public class Student {
private String foreName;
private String surName;
private int studentID;
//declaring the variables needed for my student
public Student (String foreName, String surName, int studentID)
{
this.foreName = foreName;
this.surName = surName;
this.studentID = studentID;
}
//constructor to set out what a student needs
public String getForeName() {
return foreName;
}
public String getSurName() {
return surName;
}
public int getStudentID() {
return studentID;
}
public void setForeName(String foreName) {
this.foreName = foreName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
// getters and setters for my variables
public String toString ()
{
return getClass().getName() + "foreName = " + foreName + "surName = " + surName + "studentID = " + studentID;
}
//my toString method
}
REGISTRY FILE CODE:
import java.util.*;
public class Registry {
LinkedList<String> studentList
= new LinkedList<String>();
//setting my type parameter
public Registry() {}
//empty constructor to hold arguements
public void addStudent(String aStudent)
{
this.studentList.addLast(aStudent);
}
public void deleteStudent(int studentID)
{
//????
}
#Override public String toString()
{
return "Registry";
}
public String format()
{
}
REGISTRY TESTER FILE CODE:
import java.util.*;
public class RegistryTester {
public static void main (String[] args)
{
LinkedList<String> studentList
= new LinkedList<String>();
System.out.println("Test 1");
System.out.println("Methods tested: addStudent, constructor");
System.out.println("********************");
studentList.add("Joe Perkins 123");
studentList.addLast("Shilpa Gupta 1234");
studentList.addLast("Seany Ray 12345");
// adding 3 students to my list
System.out.println(studentList);
}
}

Define the List as a List of Student
LinkedList<Student> studentList = new LinkedList<Student>();
Override the hashCode() and equals() method in Student class.
public boolean equals(Object obj) {
if (obj instanceof Student) {
return studentID == ((Student)obj).getStudentID();
}
return false;
}
public int hashCode() {
return studentID;
}
Define methods:
public void addStudent(Student aStudent)
{
this.studentList.addLast(aStudent);
}
public void deleteStudent(Student astudent)
{
this.studentList.remove(aStudent)
}

First you should make your LinkedList for type Student:
LinkedList<Student>
Then to remove a student, you could :
go through the list, find out the student object with same id, remove it
override equals() and hashcode() method in your Student class, then
public void deleteStudent(int studentID)
{
//getStudent object (stu) By the given ID
studentList.remove(stu);
}
use Map, (HashMap or LinkedHashMap) instead of LinkedList, key is the studentId, value is the studentObject. This will make add/remove easier.

If you have a Collection (in your case a LinkedList) of Students and call remove(studentToRemove) on it, Java will compare each object with studentToRemove by using its equals() method.
In your case, you haven't written an equals() method, hence the one for Object is used. If indeed a student is uniquely identified by its studentId (that is, two Student instances with the same studentId are always the same student) you should override the equals() metod and check for equality using that field.
Read about equals() and hashCode().
Another alternative would be to iterate the list until you find the match, and then remove the student from the list.

Related

Static Method addStudents

So I need help with this part of JAVA in my COP class OOP programming.
First is that I need to change the addStudent to static method but the code will not run because the this.student is not static which makes no sense because it already private static
import java.util.Arrays;
public class InitializerDemo {
public static final int MAX_STUDENTS = 10;
private static Student[] students;
private Instructor instructor;
private static int numStudents = 0;
// default constructor
public InitializerDemo() {
}
// instructor mutator
public void setInstructor(Instructor instructor) {
this.instructor = instructor;
}
// add a student, increment the count
//This PART!!! HELP
public static void addStudent(Student s) {
this.students[numStudents++] = s;
}
public static void main(String[] args) {
// create our aggregator object
InitializerDemo id = new InitializerDemo();
// set the instructor
id.setInstructor(new Instructor("Sally"));
// add the students
id.addStudent(new Student("Sam"));
id.addStudent(new Student("Rajiv"));
id.addStudent(new Student("Jennifer"));
id.addStudent(new Student("Test Student"));
// output
System.out.println(id);
}
public String toString() {
String s = "Instructor = " + instructor + "\n" +
"Number of students = " + numStudents + "\n" +
"Students: " + Arrays.toString(students) + "\n";
return s;
}
}
class Student {
private String name;
// instance initializer block
{
name = "noname";
}
public Student() {
}
public Student(String name) {
this.name = name;
}
public String toString() { return name; }
}
class Instructor {
private String name;
// instance initializer block
{
name = "noname";
}
public Instructor() {
}
public Instructor(String name) {
this.name = name;
}
public String toString() { return name; }
}
I need help with that addStudent Method
These are the instructions and sorry to confuse all you guys and thank you for putting time to help me
change the instance variables representing the number of students and the Student array in the aggregator object to private static variables.
• change the addStudent method in the aggregator object from an instance method to a static method
• Remove all initialization/instantiation operations from the aggregator object’s default constructor; the constructor can simple be an empty method { }
• provide a static initializer block in the aggregator object which does the following:
o initializes the number of students to 0
o instantiates the student array
o adds a single student named “Test Student” to the array using the addStudent method
Change
this.students[numStudents++] = s;
to
students[numStudents++] = s;.
I believe that should work.
You also have to initialize the students, so change
private static Student[] students;
to
private static Student[] students = new Student[MAX_STUDENTS];

Why do I keep getting a Null Exception Error?

I have three classes in my program. Ship.java, Cabin.java and Passenger.java. According to the program a single cabin can hold upto a maximum of 3 passengers. I'm trying to set passenger details but i keep getting this error
Cannot invoke "classes.Passenger.setFirstName(String)" because
"classes.Main.myShip[0].passenger[0]" is null at
classes.Main.main(Main.java:22)
Ship.java
public class Ship
{
public static Scanner scanner = new Scanner(System.in);
public static Cabin[] myShip = new Cabin[12];
public static void main(String[] args)
{
for (int count = 0; count < 12; count++)
{
myShip[count] = new Cabin();
}
myShip[0].passenger[0].setFirstName("a");
}
}
Cabin.java
public class Cabin
{
int cabinNumber;
Passenger[] passenger = new Passenger[3];
public Cabin()
{
}
public Cabin(int cabinNumber, Passenger[] passenger)
{
this.cabinNumber = cabinNumber;
this.passenger = passenger;
}
public void setCabinNumber(int cNumber)
{
cabinNumber = cNumber;
}
public int getCabinNumber()
{
return cabinNumber;
}
}
Passenger.java
public class Passenger
{
String firstName;
String lastName;
int expenses;
public Passenger()
{
}
//Constructors
public Passenger(String cabinFirstName, String cabinLastName, int pExpenses)
{
firstName = cabinFirstName;
lastName = cabinLastName;
expenses = pExpenses;
}
public void setFirstName(String cabinFirstName)
{
firstName = cabinFirstName;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String cabinLastName)
{
lastName = cabinLastName;
}
public String getLastName()
{
return lastName;
}
public void setExpenses(int pExpenses)
{
expenses = pExpenses;
}
public int getExpenses()
{
return expenses;
}
}
Please be kind enough to help me out.
Your model is wrong. A ship can (and does) have cabins with no occupants. You have provided no way to have unoccupied cabins. Your cabins need to be fully booked before the ship can be built!
I would consider redefining your Cabin class to be constructed empty -- which means it would have a constructor with a signature like Cabin(), and then provide a way to assign Passengers to Cabins. Maybe this would be a method in the Cabin class, like
boolean assignPassenger(Passenger p) {
... check occupancy...
... return false if full up ...
... otherwise add 'p' to the passenger array ...
... and return true ...
}
You're halfway there in that you're attempting to set the Cabins in the Ship by using a Cabin() constructor -- which is essentially an empty Cabin -- but you have not actually implemented a constructor with that signature.
What I'm getting at here is that, rather than just tweaking some Java, I think you should rethink it a bit. You'd want, I think, to be able to have unoccupied cabins and to be able to determine which cabins are occupied.

How to remove an element of an arraylist from input

how can i remove a student from the course
i tried enrolledStudents.remove("");
since the user will have to put the name of the student that previously enrolled to drop him.
public class Course {
public String courseName;
public int maxNumberofStudentsAllowedtoEnroll=100;
private ArrayList<String> enrolledStudents = new ArrayList<String>(100);
public Course(String courseName){
this.courseName = courseName;
}
public void addStudent(String student){
if(enrolledStudents.size() == maxNumberofStudentsAllowedtoEnroll){
System.out.println("You have reached the maximum numbers of students allowed in a course! \n"
+ "Max allowed: "+maxNumberofStudentsAllowedtoEnroll);
return;
}
enrolledStudents.add(student);
}
public int getNumberStudents(){
return enrolledStudents.size();
}
public void showStudents(){
for(int i=0; i<enrolledStudents.size(); i++){
System.out.println(enrolledStudents.get(i));
}
}
public void dropStudent(String student){
enrolledStudents.remove(" ");
}
ive searched up on the net about it. But all the elements of an array are already assigned.
im sorry if im not clear, basically what i want to do is:
if i add a student when i press 1, and then type: "john"
and then do the same with: "albert"
how do i do so that when i press 2 and enter the name of the student to drop, in this case: "john"
So that when I press 3 to view the students only "albert" shows up.
Try to remove the quotation marks "" from the .remove method and use the String parameter student inside the remove method. Below you may find the answer. Hope this helps.
public class Course {
public String courseName;
public int maxNumberofStudentsAllowedtoEnroll=100;
private ArrayList<String> enrolledStudents = new ArrayList<String>(100);
public Course(String courseName){
this.courseName = courseName;
}
public void addStudent(String student){
if(enrolledStudents.size() == maxNumberofStudentsAllowedtoEnroll){
System.out.println("You have reached the maximum numbers of students allowed in a course! \n"
+ "Max allowed: "+maxNumberofStudentsAllowedtoEnroll);
return;
}
enrolledStudents.add(student);
}
public int getNumberStudents(){
return enrolledStudents.size();
}
public void showStudents(){
for(int i=0; i<enrolledStudents.size(); i++){
System.out.println(enrolledStudents.get(i));
}
}
public void dropStudent(String student){
enrolledStudents.remove(student);
}
Instead of "" just write student.
public void dropStudent(String student){
enrolledStudents.remove(student);
}
that's it. You can check it by calling System.out.println(course.enrolledStudents); before and after dropStudent function.

Array object and element?

this class works:
public class Undergrad extends Student{
private int year;
private int numOfCourses=0;
private Course[] courses=new Course[4];
public Undergrad(int year,String name,String major,double gpa){
super(name,major,gpa);
this.year=year;
}
public int getYear(){
return year;
}
public void setYear(int year){
this.year=year;
}
public String getName(){
return name;
}
public String getMajor(){
return major;
}
public double getGpa(){
return gpa;
}
public void setGpa(double gpa){
this.gpa=gpa;
}
public Course[] getCourses(){
return courses;
}
public void addCourses(Course course){
if(numOfCourses>=4){
System.out.println("Student can not study");
} else{
courses[numOfCourses]=course;
numOfCourses++;
}
}
public void printCourses(){
for(int i=0;i<numOfCourses;i++){
System.out.println(courses[i].toString());
}
}
public String toString(){
return "Student name"+name+"courses"+numOfCourses;
}
}
but I was just wondering shouldn't "course" have an "s" so it becomes courses, so it can become the same as the name in the array "courses". Also is the printCourse method the same as the System.out.print method?
public void addCourses(Course course)
Course is simply the name of the class. Even if there are plenty of Course objects, the name stays the same.
As of courses is the name of the object's reference so you're free to choose it while creating it.
If your question is why in addCourses(Course course) course does not have an s, it is because it is a reference to a Course object and not to the array.
courses[numOfCourses]=course
Here, we're adding course to the courses array of Course objects.
To your question, it doesn't really make any difference. Your 'addCourses' method is not a setter or getter method, so should in future you want to use the class for any purposes that imply serialization you will be fine.
But just for readability you could rename it to void addCourse(Course c).
In addition, you could guard against potential null argument using the Optional class added in Java 8.
public void addCourse(Course c){
if(numOfCourses>=4){
System.out.println("Student can not study");
} else{
courses[numOfCourses]=Optional.ofNullable(c).orElse(new Course(argument 1, argument 2, argument etc));
numOfCourses++;
}
}

how to create a collection or array of my custom objects

I have a class called anItem and it allows me to model variables into an object.
I have many of these objects and i want to put them into a colection. What is the class code for the collection?
Here is what i have:
package com.rest.myproject;
public class anItem
{
String name;
String age;
public anItem()
{
super();
}
//methods
public String getName()
{
return this.name;
}
public void setName(String newName)
{
this.name=newName;
}
public String getAge()
{
return this.age;
}
public void setAge(String newAge)
{
this.age=newAge;
}
}
Public class aCollectionOfItems
{
anItem[] item; ->should I create a array of items to add and remove from?
public aCollection()
{
super();
}
//How do I add aItem to my collection, create an array of items?
}
Use a List to hold your items.
public class Item {
private String name;
private String age;
//methods
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return this.age;
}
public void setAge(String age) {
this.age = age;
}
}
public class CollectionOfItems {
List<Item> items = new ArrayList<>();
public void addItem(Item item) {
items.add(item);
}
}
public class CollectionOfItems {
int size = 10; //any size that is required.
private final Item[] item;
public aCollection(){
super();
item = new Item[size];
}
}
Java Collections can also be used to hold the items, as a replacement for Arrays.
I suggest on reading through Oracle's documentation / tutorial of Java collections:
https://docs.oracle.com/javase/tutorial/collections/
A few brief examples:
ArrayList - This is a list of objects, stored as an array.
Useful form quick ransom access
LinkedList - This is also a list. Useful if you don't know the size of the list ahead of time, but it's
not efficient for random access
HashSet - This is a set. Only one of each items is allowed. Items are compared using hashCode() and equals().
TreeSet - This is also a set. Items are sorted, so you can
iterate them in some order.
HashMap - This is a key/value collection.
For example HashMap is will store/retrieve
TreeMap - This is also key/value store. Items are sorted.

Categories

Resources