This question already has answers here:
How do I remove objects from an array in Java?
(20 answers)
Closed 5 years ago.
How can I remove a student from the course by using the drop method down below? I tried by accessing the roll book for the course parameter.
But I do not how to remove the student id from the roll book.
public static class Student {
private int studentID;
private String first;
private String last;
private int credits;
private boolean graduate;
public Student(int id, String first, String last, boolean graduate) {
this.studentID = id;
this.first = first;
this.last = last;
this.graduate = graduate;
}
public int getID() { return studentID; }
public String getFirstName() { return first; }
public String getLastName() { return last; }
public int getCredits() { return credits; }
public boolean isGraduate() { return graduate; }
public void setCredits(int credits) { this.credits = credits; }
public String toString() { return "[" + studentID + "] " + first + " " + last; }
public boolean isEnrolled(Course c) {
return (c.findRollBookEntry(this.getID()) != null);
}
public void drop(Course c) {
for(int i = 0; i<c.getRollBook().length; i++){
c.findRollBookEntry(i).getStudent();
}
}
}
If you are using an array list and passing new objects each time a data is entered you can iterate through the arraylist on the delete function and do something like
If(i.getID()==id_entered) {i.remove();}
Related
So here is assignment :
A student entity has a name and an address (both represented by an object of class Name and Address), in addition to a university ID, and a course schedule represented by an ArrayList of Courses
Your code should not allow the creation of Two students with the same university ID
So I'm thinking of using ArrayList to hold a list of student and check if student exists or not before create a new student. sorry, this is my first question so I'm trying my best to explain it:
This is my Address class:
public class Address {
private int streetNumber;
private String streetName;
private String city;
private String state;
private int province;
private String country;
public Address (int streetNumber,String streetName,String city,String state,int province,String country)
{
this.streetNumber=streetNumber;
this.streetName=streetName;
this.city=city;
this.state=state;
this.province=province;
this.country=country;
}
public int getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(int streetNumber) {
this.streetNumber = streetNumber;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getProvince() {
return province;
}
public void setProvince(int province) {
this.province = province;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String toString() {
return " [streetNumber=" + streetNumber + ", streetName=" + streetName
+ ", city=" + city + ", state=" + state + ", province="+province+", country="
+ country + "]";
}
public boolean equals(Address add)
{
if(add==null)
{
return true;
}
if(this.getClass()!=add.getClass())
{
return false;
}
Address address=(Address) add;
return streetNumber==address.streetNumber &&
province==address.province && streetName.equals(address.streetName)
&& city.equals(address.city)&& state.equals(address.state)&& country.equals(address.country);
}
}
This is my Name class
public class Name {
private String firstName;
private String lastName;
private char middle;
public Name (String fiName,String laName, char middle)
{
this.firstName=fiName;
this.lastName=laName;
this.middle=middle;
}
public String getFirst()
{
return firstName;
}
public void setFirst(String first)
{
firstName=first;
}
public String getLast()
{
return lastName;
}
public void setLast(String last)
{
lastName=last;
}
public char getMiddle()
{
return middle;
}
public void setMiddle(char midd)
{
middle=midd;
}
/*public String toString()
{
return "[First Name= "+ firstName +" Last Name "+ lastName+" Middle Name "+ middle +"";
}*/
}
This is my Student class:
public class Student {
private int studentId;
private Name name;
private Address address;
boolean a;
ArrayList<Course> courseSchedule = new ArrayList<Course>();
ArrayList<Student> student=new ArrayList<Student>();
public Student(String fiName,String laName, char middle,int stNumber,String stName,String city,String state,int province,String country,int id)
{
if(student.contains(id))
{
System.out.println("Student cannot be same id");
}
else
{
address= new Address(stNumber,stName,city,state,province,country);
name=new Name(fiName,laName,middle);
this.studentId=id;
student.add();
}
}
public int getID()
{
return studentId;
}
public void setId(int id)
{
this.studentId = id;
}
public ArrayList<Course> getCourseSchedule()
{
return courseSchedule;
}
public void setCourseSchedule(ArrayList<Course> courseSchedule)
{
this.courseSchedule = courseSchedule;
}
public void addCourse(Course c) {
courseSchedule.add(c);
}
public void dropCourse(Course course) {
courseSchedule.remove(course);
}
}
My question is how can you add Student Object into Student ArrayList
and how can I check if the Student Id exists in ArrayList with contains() method
student.contains(id) this line right here it does not seem to be right
I hope im explain my question a little clear now. Sorry for my english also.
You would not keep a list of Student objects within the class for Student. Your ArrayList<Student> student=new ArrayList<Student>(); does not belong there.
You would have another structure or collection kept elsewhere named something like StudentBody. When a student is instantiated, it is added to the StudentBody collection.
List< Student > studentBody = new ArrayList< Student >() ; // This list is stored somewhere else in your app.
You could loop a List of Student objects in the StudentBody object. For each you would access the UniversityId member field and compare to your new one being added.
Or you could use a Map, where the key is a UniversityId object and the value is a Student object. Check for an existing key before adding.
These solutions ignore the important issue of concurrency. But that is likely okay for a homework assignment in a beginning course in programming.
Use A HashMap() for collecting information based on unique Ids.
public class Student {
private int studentId;
private Name name;
private Address address;
private static HashMap<Integer,Student> students = new ConcurrentHashMap<>(); // Make a static Map so all objectrs shared same data
public Student(String fiName,String laName, char middle,int stNumber,String stName,String city,String state,int province,String country,int id)
{
if(students.contains(id))
{
System.out.println("Student can be same id");
}
else
{
address= new Address(stNumber,stName,city,state,province,country);
name=new Name(fiName,laName,middle);
this.studentId=id;
students.put(id,this); // use this to add current object
}
}
I have created a simple Queue of type which is also contains a print() function to it.
public class ArrayQueue implements Queue {
private T[] theArray;
private int currentSize;
private int front;
private int back;
private static final int DEFAULT_CAPACITY = 10;
public ArrayQueue() {
theArray = (T[]) new Object[DEFAULT_CAPACITY];
currentSize = 0;
front = 0;
back = -1;
}
public boolean isEmpty() {
return currentSize == 0;
}
public T dequeue() throws EmptyQueueException {
if (isEmpty())
throw new EmptyQueueException("ArrayQueue dequeue error");
T returnValue = theArray[front];
front = increment(front);
currentSize--;
return returnValue;
}
public void enqueue(T x) {
if (currentSize == theArray.length)
doubleQueue();
back = increment(back);
theArray[back] = x;
currentSize++;
}
private int increment(int x) {
if (++x == theArray.length)
x = 0;
return x;
}
public void print() {
if (isEmpty()) {
System.out.printf("Empty queue\n");
return;
}
System.out.printf("The queue is: ");
for (int i = front; i != back; i = increment(i)) {
System.out.print(theArray[i] + " ");
}
System.out.print(theArray[back] + "\n");
}
I have also created a Song object with 3 variables
public class Song {
private int id;
private String name;
private int likes;
public Song() {
this(1,"Test",10);
}
public Song(int id,String name, int likes) {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
Is there a way modify this function in order to print a specific object's information or do i need to write a different print method during my implementation?
For example i would like my Print method to show all the objects variables , if i call just like this is will only get the object pointer
ArrayQueue<Song> arrayQueue = new ArrayQueue<Song>();
Queue<Song> queue = arrayQueue; //arrayQueue instance is also a Queue
Song s = new Song();
arrayQueue.enqueue(s);
arrayQueue.print();
Result is
The queue is: Song#15db9742
My modification would print :
The queue is : 1 Test 10
You need to override the toString() method of Song.
For example, add this to Song:
#Override
public String toString() {
return id + " " + name + " " + likes;
}
I'm trying to do this exercise: i have a student that has a name,surname and a number, i want to order the students by number..if i want to order by name or surname it seems easy but with number i don't know how to do..
this is my code:
public class Student implements Comparable<Student> {
private String name;
private String surname;
private int number;
public Student(String n, String s, int m) {
name = n;
surname = s;
number = m;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getmatricola() {
return number;
}
//CompareTo Name
public int compareTo(Student otherObject) {
return name.compareTo(otherObject.getName());
}
}
//TESTER
ArrayList<Student> list = new ArrayList<Student>();
System.out.print("\n ORDER BY NUMBER \n");
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
Student s = list.get(i);
String std = s.getAll();
System.out.println(std);
}
You can implement something like:
public int compareTo(Student otherObject) {
return Integer.compare(this.number, otherObject.getNumber());
}
So why you number is an int you can substract the number and return the difference:
public class Student implements Comparable<Student> {
private String name;
private String surname;
private int number;
public Student(String n, String s, int m) {
name = n;
surname = s;
number = m;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getmatricola() {
return number;
}
//CompareTo number
public int compareTo(Student otherObject) {
return number - otherObject.getmatricola();
}
}
Try doing this...should work
//CompareTo Name
public int compareTo(Student otherObject) {
if( this.getmatricola() > otherObject.getmatricola())
return 1;
else
return -1;
}
I am trying to get the length of the longest first name and saving it as int longest, but my code is not properly fetching the first names from my class Student
here is my code:
public static int findLongestFirstName(ArrayList<Student> studentList)
{
int longest = 0;
for (int i = 0; i < studentList.size(); i++)
{
if (studentList.get(i).getFirstName.length() > longest);
{
longest = studentList.get(i).getFirstName.length();
}
}
return longest;
}
Here is where I am fetching my variables:
public class Student
{
private int IDnum;
private String firstName;
private String lastName;
private int gradYear;
private double gradePoint;
public Student(int ID, String first, String last, int year, double GPA)
{
IDnum = ID;
firstName = first;
lastName = last;
gradYear = year;
gradePoint = GPA;
}
public int getID()
{
return IDnum;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public int getYear()
{
return gradYear;
}
public double getGPA()
{
return gradePoint;
}
}
getFirstName is not a variable, it's a method. Java syntax requires parentheses when calling a method (even if the method takes no arguments):
if (studentList.get(i).getFirstName().length() > longest);
^^
(and on the next line).
By the way, you can replace the entire if construct with:
longest = Math.max(studentList.get(i).getFirstName().length(), longest);
To simplify this further, you could use a for-each loop:
public static int findLongestFirstName(ArrayList<Student> studentList)
{
int longest = 0;
for (Student student : studentList) {
longest = Math.max(student.getFirstName().length(), longest);
}
return longest;
}
Your code seems fine however there is a semi colon at the end of your if statement which is causing the issue.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
This is Java, using BlueJ.
I have four classes called Person, Letter, Address and PhoneNumber. In each, I override the toString() method to return a concatenated string of the values I want from the class. When calling the Letter toString(), it is returning null on all values.
The idea is to use the hard coded information, pass it into the appropriate class, and return it in a standard letter format.
Am I headed in the right direction for printing out the information hard coded, or should I go a different route? This is a homework problem, but I feel I have hit a brick wall.
Here are the classes:
public class Person
{
private static String aPerson;
private String first;
private String middle;
private String last;
private Address address;
private PhoneNumber phone;
public String getFirst()
{
return this.first;
}
public void setFirst(String FirstName)
{
this.first = FirstName;
}
public String getMiddle()
{
return this.middle;
}
public void setMiddle(String MiddleName)
{
this.middle = MiddleName;
}
public String getLast()
{
return this.last;
}
public void setLast(String LastName)
{
this.last = LastName;
}
public Address getMyAddress()
{
return this.address;
}
public void setMyAddress(Address Address)
{
this.address = Address;
}
public PhoneNumber getMyPhoneNum()
{
return this.phone;
}
public void setMyPhoneNum(PhoneNumber Number)
{
this.phone = Number;
}
public Person()
{
aPerson = getFirst() + getMiddle() + getLast() + getMyAddress() +
getMyPhoneNum();
}
public String toString()
{
return aPerson;
}
}
PhoneNumber:
public class PhoneNumber
{
private String number;
private int areaCode = 0;
private int phonePrefix = 0;
private int phoneLineNum = 0;
private int phoneExtension = 0;
public String getNumber()
{
return number;
}
public void setNumber(String Number)
{
number = Number;
}
public int getAreaCode()
{
return areaCode;
}
public void setAreaCode(int AreaCode)
{
areaCode = AreaCode;
}
public int getPrefix()
{
return phonePrefix;
}
public void setPrefix(int Prefix)
{
phonePrefix = Prefix;
}
public int getPhoneLineNumber()
{
return phoneLineNum;
}
public void setLineNum(int PhoneNumber)
{
phoneLineNum = PhoneNumber;
}
public int getExtension()
{
return phoneExtension;
}
public void setExtension(int Extension)
{
phoneExtension = Extension;
}
}
Address:
public class Address
{
private String state;
private String anAddress;
private String address;
private String city;
private int zip = 0;
public String getState()
{
return state;
}
public void setState(String State)
{
state = State;
}
public String getAddress()
{
return address;
}
public void setAddress(String Address)
{
address = Address;
}
public String getCity()
{
return city;
}
public void setCity(String City)
{
city = City;
}
public int getZip()
{
return zip;
}
public void setZip(int Zip)
{
zip = Zip;
}
public Address()
{
anAddress = getState() + getAddress() + getCity() + getZip();
}
public String toString()
{
return this.anAddress;
}
}
Letter:
public class Letter
{
private Person to;
private Person from;
private String body;
private String finishedLetter;
public Person getTo()
{
return to;
}
public void setTo(Person newValue)
{
to = newValue;
}
public Person getFrom()
{
return from;
}
public void setFrom(Person newValue)
{
from = newValue;
}
public String getBody()
{
return body;
}
public void setBody(String newValue)
{
body = newValue;
}
public Letter()
{
finishedLetter = getTo() + " \n" + getFrom() + " \n" + getBody();
}
public String toString()
{
return finishedLetter;
}
}
And main:
public class MainClass
{
public static void main(String args[])
{
PhoneNumber phone1 = new PhoneNumber();
phone1.setAreaCode(417);
phone1.setPrefix(447);
phone1.setLineNum(7533);
phone1.setExtension(0);
PhoneNumber phone2 = new PhoneNumber();
phone2.setAreaCode(210);
phone2.setPrefix(336);
phone2.setLineNum(4343);
phone2.setExtension(9850);
Address address1 = new Address();
address1.setState("MO");
address1.setAddress("1001 East Chestnut Expressway");
address1.setCity("Springfield");
address1.setZip(65807);
Address address2 = new Address();
address2.setState("TX");
address2.setAddress("4800 Calhoun Road");
address2.setCity("Houston");
address2.setZip(77004);
Person person1 = new Person();
person1.setFirst("Shane");
person1.setMiddle("Carroll");
person1.setLast("May");
person1.setMyAddress(address1);
person1.setMyPhoneNum(phone1);
Person person2 = new Person();
person2.setFirst("Ted");
person2.setMiddle("Anthony");
person2.setLast("Nugent");
person2.setMyAddress(address2);
person2.setMyPhoneNum(phone2);
Letter aLetter = new Letter();
aLetter.setTo(person2);
aLetter.setFrom(person1);
aLetter.setBody("This is the body");
System.out.println(aLetter.toString());
}
}
Your Letter constructor is calling methods such as getTo() and getFrom() before those fields have been filled. Don't do this since your finishedLetter String will never be correctly "finished". i.e.,
public Letter()
{
finishedLetter = getTo() + " \n" + getFrom() + " \n" + getBody();
}
will always result in null + "\n" + null + "\n" + null
Perhaps that sort of code should be in the toString() method instead.
When your letter is constructed using new Letter(), it initializes its instance field finishedLetter with several null values. Because to, from, and body haven't yet been set with their corresponding setters, their getters return null, resulting in finishedLetter being equal to "null \nnull \nnull".
To fix this, I one approach is to define the finishedLetter in the toString() method itself. This will both fix the issue and take a more object-oriented approach to the program design.
// remove constructor (if you wish) and finishedLetter field
public String toString() {
return getTo() + " \n" + getFrom() + " \n" + getBody();
}
An even better approach is to require to, from, and body, as parameters in the Letter constructor.
// remove finishedLetter field
public Letter(Person to, Person from, String body) {
this.to = to;
this.from = from;
this.body = body;
}
public String toString() {
return getTo() + " \n" + getFrom() + " \n" + getBody();
}