I need to write a method that removes students from the ArrayList (myRoster) by student ID. If the student ID doesn't exist, the method should print an error message indicating that it is not found. I have written a remove method where I'm able to remove item by index. The error message 'Student with ID 3 was not found' is returning 6 times (3 from first remove and 3 from second error message). But I want to get one error message for second remove method which I'm calling in main method. A little help would be much appreciated.
Student Class
public class Student {
private int StudentID;
private String FirstName;
private String LastName;
private String Email;
private int age;
private int[] Grades;
//Constructor
public Student(int S_ID,String fName,String lName,String email,int Age,
int[] grade){
setStudentID(S_ID);
setFirstName(fName);
setLastName(lName);
setEmail(email);
setAge(Age);
setGrade(grade);
}
//Accessor Methods (get methods)
public int getStudentID(){
return StudentID;
}
public String getFirstName(){
return FirstName;
}
public String getLastName(){
return LastName;
}
public String getEmail(){
return Email;
}
public int getAge(){
return age;
}
public int[] getGrades(){
return Grades;
}
//Mutator methods (set methods)
public void setStudentID(int StudentID){
this.StudentID=StudentID;
}
public void setFirstName(String FirstName){
this.FirstName=FirstName;
}
public void setLastName(String LastName){
this.LastName=LastName;
}
public void setEmail(String Email){
this.Email=Email;
}
public void setAge(int age){
this.age=age;
}
public void setGrade(int Grade[]){
this.Grades=Grade;
}
}
Roster Class
import java.util.ArrayList;
public class Roster {
private static ArrayList<Student> myRoster= new ArrayList<>();
public static void main(String[] args) {
add(1,"John", "Smith", "John1989#gmail.com", 20, 88,79, 59);
add(2,"Suzan", "Erickson", "Erickson_1990#gmailcom",19,91,72,85);
add(3,"Jack","Napoli","The_lawyer99yahoo.com",19,85,84,87);
add(4,"Erin", "Black","Erin.black#comcast.net",22,91,98,82 );
add(5,"Henry","Adam","adam1#gmail.com",25,85,84,79);
remove(3);
remove(3);//expected: This should print a message saying such a student with this ID was not found
}
public static void add(int S_ID,String fName,String lName,String email,int
Age, int grade1, int grade2, int grade3){
int[] Grades={grade1, grade2,grade3};
Student newStudent= new Student(S_ID, fName, lName, email, Age, Grades);
myRoster.add(newStudent);
}
public static void remove(int StudentID){
for (int i = 0; i < myRoster.size(); i++){
if(i == StudentID){
myRoster.remove(i);
}else{
System.out.println("Student with ID "+StudentID+" was not found");
}
}
}
}
}
You should never attempt to remove an element from a list while iterating over it.
Your comparison is incorrect, reason being that you're comparing the for loop control variable i with the parameter StudentID rather it should be if(myRoster.get(i).getStudentID == StudentID).
The reasoning as to why the text "Student with ID "+StudentID+" was not found" is being printed to the console multiple times is because you've inserted it inside the loop, meaning each time the parameter StudentID doesn't match the value that it's being compared to, it will print the same message...
To accomplish your task you can simply use the ArrayList#removeIf method to remove the Student with the specified StudentID, else if the ArrayList#removeIf returns false then you can print the appropriate message as shown within the solution below.
public static void remove(int StudentID) {
if (!myRoster.removeIf(s -> s.getStudentId() == StudentID))
System.out.println("Student with ID " + StudentID + " was not found");
}
Your remove method is currently giving the error message once for every student in the list that doesn't have the desired student ID.
for (int i=0;i<myRoster.size();i++){
if(i==StudentID){
myRoster.remove(i);
}else{
System.out.println("Student with ID "+StudentID+" was not found"); }
That print statement is called any time the student at index i does not have the desired ID, not when there are no students that have that ID.
An easy way to fix this would be to put a boolean at the start of the method and set it to false. Then, in the if (i == StudentID) block, remove the student and set the value to true. Then, after the loop is complete, check if the boolean is true; if it is true, then the desired student has been removed. If it is still false, then there is no student with the desired ID.
It should look something like this:
public static void remove(int studentID) {
boolean studentFound = false;
for (int i=0;i<myRoster.size();i++){
if(i==StudentID){
myRoster.remove(i);
i--; // you have to decrement this value to account for the missing item
studentFound = true; // student with desired ID is removed
}
if (!studentFound) System.out.println("Student with ID "+StudentID+" was not found");
}
You problem seems to be that your loop in the remove() method isn't looping over studentIDs but just the looping index. You should loop over studentIDs. Your code prints each time an ID doesn't match the given ID. That's why you get multiple print messages. You should instead only print if no one matches (i.e. roster size doesn't change).
public static void remove(int StudentID){
int initialSize = myRoster.size(); //store initial size of roster to check if it changes
for (int i=0;i<myRoster.size();i++){
if(myRoster.get(i).getStudentID == StudentID){
myRoster.remove(i);
}
}
//checks if a student was removed which means the ID was found.
if(initialSize == myRoster.size()){
System.out.println("Student with ID "+StudentID+" was not found");
}
}
You can use Iterator interface as well for your purpose as shown below.
public static void remove(int StudentID) {
Iterator<Student> it = myRoster.iterator();
while(it.hasNext()) {
Student stud = (Student)it.next();
if (stud.getStudentID() == StudentID) {
it.remove();
return;
}
}
System.out.println("Student with ID " + StudentID + " was not found");
}
Yes you can do this ,please some add things in your Student class
public class Student {
private int StudentID;
private String FirstName;
private String LastName;
private String Email;
private int age;
private int[] Grades;
public Student(int S_ID ){
this.setStudentID(S_ID);
}
//Constructor
public Student(int S_ID,String fName,String lName,String email,int Age,
int[] grade){
setStudentID(S_ID);
setFirstName(fName);
setLastName(lName);
setEmail(email);
setAge(Age);
setGrade(grade);
}
//Accessor Methods (get methods)
public int getStudentID(){
return StudentID;
}
public String getFirstName(){
return FirstName;
}
public String getLastName(){
return LastName;
}
public String getEmail(){
return Email;
}
public int getAge(){
return age;
}
public int[] getGrades(){
return Grades;
}
//Mutator methods (set methods)
public void setStudentID(int StudentID){
this.StudentID=StudentID;
}
public void setFirstName(String FirstName){
this.FirstName=FirstName;
}
public void setLastName(String LastName){
this.LastName=LastName;
}
public void setEmail(String Email){
this.Email=Email;
}
public void setAge(int age){
this.age=age;
}
public void setGrade(int Grade[]){
this.Grades=Grade;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return StudentID == student.StudentID;
}
#Override
public int hashCode() {
return StudentID;
}
}
and in main area class you can do
public class Test {
public static void main(String []args){
List<Student> list = new ArrayList<>();
list.add(new Student(1,"a","a","a",1, new int[]{1}));
list.add(new Student(2,"b","b","b",2, new int[]{2}));
list.remove(new Student(1));
list.forEach(System.out::println);
}
}
Output
com.traveliko.platform.web.frontend.Student#2
Related
We have an activity that will store and display the information of an employee.
I've already created no-modifier class named Person and a public class named Employee which is the the main method. My problem is I don't know how to make the boolean in the class Person which will be used in the main method with a scanner.
class Person {
private String name;
private int contactNum;
private boolean status;
public boolean isRegular;
public String getName(){
return name;
}
public int getContactNum(){
return contactNum;
}
public void setName(String name){
this.name=name;
}
public void setContactNum(int contactNum){
this.contactNum=contactNum;
//how to make the boolean of status and isRegular?
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Person P = new Person();
System.out.println("Type employee's name, contact number");
System.out.println("Press Enter after every input");
P.setName(input.nextLine());
P.setContactNum(input.nextInt());
System.out.println("Press Y if employee is regular or N if not");
//how to use boolean here that comes from the class Person?
System.out.println("Name: "+ P.getName());
System.out.println("Contact Number: "+ P.getContactNum());
System.out.println("Status:" + this is where the user is ask to Press Y if employee is regular or N if not )//the status is if the employee is regular or not.
My suggestion for your code:
System.out.println("Press Y if employee is regular or any other key if not");
P.setRegular(input.nextLine().equalsIgnoreCase("Y"));
Your constructor
public class Person {
private String name;
private int contactNum;
private boolean status;
private boolean isRegular;
//No arg constructor
public Person() {
}
//Full arg constructor
public Person(String name, int contactNum, boolean status, boolean isRegular) {
this.name = name;
this.contactNum = contactNum;
this.status = status;
this.isRegular = isRegular;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getContactNum() {
return contactNum;
}
public void setContactNum(int contactNum) {
this.contactNum = contactNum;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public boolean isRegular() {
return isRegular;
}
public void setRegular(boolean regular) {
isRegular = regular;
}
}
Edit
I've noticed an error in the above code and fixed it. This line should be:
P.setRegular(input.next().equalsIgnoreCase("Y"));
You can print booleans as is just like any other Java primitive. `
System.out.println("Status:" + P.isRegular());
would print Status: true or Status: false.
If you want it to print Status: Yes or Status: No, you could do something like this:
System.out.println("Status: ".concat((P.isRegular())?("Yes"):("No")));
So I am creating a program that reads customer details and order details from two different files. I created methods to read the file, store the data in the object of customers and then add the object of customers into linkedlist.. Now when I try doing the same for order file, I am getting the wrong output. so in the code shown below, I am trying to check if the customer name entered in order file matches the name stored in customer linkedlist.. So say I have two rows in the order.txt file:
Ord101 true James
Ord102 false Jim
with what I have done, I get the following output:
Ord102 false Jim
Ord102 false Jim
instead of getting the correct output which would be:
Ord101 true James
Ord102 false Jim
because both, James and Jim are names present in Customer file and linkedlist. So here is my code for reading order file:
public void readFileOrder() {
Scanner y;
String b,c,d;
LinkedList<Customers> list=new LinkedList<Customers>(); //another method was already created to add data inside list and its working so list contains data
LinkedList<order> list1=new LinkedList<order>();
Boolean isOpen;
order Order1=new order();
while(y.hasNext())
{
b=y.next();
isOpen=y.nextBoolean();
d=y.next();
System.out.println(list);
Customers customers1=new Customers();
for(int i=0;i<list.size();i++) //this is where i'm checking if the customer name in the order file matches the value in list
{
if(list.get(i).getName().equals(d))
{
customers1=list.get(i);
Order1.setCustomer(customers1);
Order1.setName(b);
Order1.setIsOpen(isOpen);
list1.add(Order1);
}
}
}
for(int j=0;j<list1.size();j++)
{
System.out.println(list1.get(j).getCustomer()+" and "+list1.get(j).getName()+" and "+list1.get(j).getIsOpen());
}
}
just in case, provided below are Customer and order class:
import java.util.LinkedList;
public class Customers {
#Override
public String toString() {
return "Customers [Name=" + Name + ", age=" + age + ", email=" + email + ", Address=" + Address + "]";
}
String Name;
int age;
String email;
String Address;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public void removeCustomer(String name2, LinkedList<Customers> list) {
for(int k=0;k<list.size();k++)
{
if(list.get(k).getName().equals(name2))
{
list.remove(list.get(k));
}
}
}
}
order class:
import java.util.LinkedList;
public class order{
String name;
Boolean isOpen;
Customers customer;
String cusName;
public order() {
super();
}
public String getName() {
return name;
}
public order(Customers customer) {
super();
this.customer = customer;
}
public void setName(String name) {
this.name = name;
}
public Boolean getIsOpen() {
return isOpen;
}
public void setIsOpen(Boolean isOpen) {
this.isOpen = isOpen;
}
public String getCustomer() {
return customer.getName();
}
public void setCustomer(Customers customer) {
this.customer=customer;
this.cusName=customer.getName();
}
}
You are adding references to the same order to the list over and over again, each time overwriting the attributes set in the previous iteration of the loop. Instead, create a new order inside the loop.
In other words, change this:
order Order1=new order();
while(y.hasNext()) {
to this:
while(y.hasNext()) {
order Order1=new order();
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
}
}
Can someone help solving this. I want to print all the object once please
public class Student {
private static String firstName;
private static String lastName;
private static int studentId;
private static String major;
private static double balance;
public Student (String fName, String lName,int id,String mjr,double blce) {
firstName = new String(fName);
lastName = new String(lName);
studentId = id;
major = new String(mjr);
balance = blce;
}
public String toString () {
return firstName + "\t" + lastName + "\t" + studentId + "\t" + major + "\t$" + balance;
}
public boolean equals (Object obj) {
if (obj instanceof Student) {
Student collegeStud = (Student) obj;
return (this.firstName.equals(collegeStud.firstName));
} else
return false;
}
public static String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public static String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public static int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public static String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public static double getBalance() {
return balance;
}
/*
* .commmm
*/
public void setBalance(double balance) {
this.balance = balance;
}
public static void main (String[] args) {
Student Mike = new Student ("Mike","Versace", 99, "CS",0.00);
Student John = new Student ("John","Sling" ,97, "Maths", 20.00);
Student Bob = new Student ("Bob","Tomson" ,57, "Physic",5.00);
System.out.println (Mike.toString() + "\n" + John.toString());
if (Mike.equals(John))
System.out.println ("Mike is John");
else
System.out.println ("Mike is NOT John");
}
}
import java.io.ObjectInputStream.GetField;
public class StudentList {
private int numberOfStudents=0;
private Student[] studentListArray;
//private int studentCount = 0;
StudentList () {
numberOfStudents=0;
studentListArray = new Student[100];
}
public void createStudent(String firstName, String lastName,int studentId, String major, double balance){
Student collegeStud = new Student(firstName, lastName, studentId, major, balance);
addStudent(collegeStud);
numberOfStudents++;
}
public void addStudent (Student collegeStud) {
studentListArray[numberOfStudents++]=new Student(collegeStud.getFirstName(), collegeStud.getLastName(),
collegeStud.getStudentId(), collegeStud.getMajor(),collegeStud.getBalance());
}
public String toString() {
String result = "";
for (int i=0; i<numberOfStudents; i++) {
result += studentListArray[i].toString() + "\n";
}
return result;
}
public Student[] getList() {
return studentListArray;
}
public int listSize() {
return numberOfStudents;
}
public Student searchForStudent (String firstName){
int index = 0;
while (index < numberOfStudents) {
if (studentListArray[index].equals(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()))) {
return studentListArray[index];
}
index++;
}
return null;
}
public static void main(String args[]) {
StudentList theList = new StudentList();
theList.addStudent (new Student ("John","Sling" ,97, "Maths", 20.00));
theList.addStudent (new Student ("Mike","Versace", 99, "CS",0.00));
theList.addStudent (new Student ("Bob","Tomson" ,57, "Physic",5.00));
//theList.createStudent(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()));
//theList.searchForStudent(new String());
System.out.println (theList.toString());
}
}
The problem is that you marked your fields as static. Remove it and the method will work as expected.
public class Student {
//non-static fields
private String firstName;
private String lastName;
private int studentId;
private String major;
private double balance;
//similar for getters, setters and toString method
}
Static members are shared amongst all objects in a class rather than being one per object. Hence each new object you create is overwriting the data of the previous one.
More info:
What does the 'static' keyword do in a class?
I have a homework assignment problem that looks like this:
(20 pts) Create a Student class with the following:
A private String variable named “name” to store the student’s name
A private integer variable named “UFID” that contains the unique ID number for this student
A private String variable named “DOB” to store the student’s date of birth
A private integer class variable named numberOfStudents that keeps track of the number of students that have been created so far
A public constructor Student(String name, int UFID, String dob)
Several public get/set methods for all the properties
getName/setName
getUFID/setUFID
getDob/setDob
Write a test program, roster.java, that keeps a list of current enrolled students. It should have methods to be able to enroll a new
student and drop an existing student.
I'm not asking anyone to do this assignment for me, I just really need some general guidance. I think I have the Student class pretty well made, but I can't tell exactly what the addStudent() and dropStudent() methods should do - should it add an element to an array or something or just increments the number of students? The code I have so far looks like this.
public class Student {
private String name;
private int UFID;
private String DOB;
private static int numberOfStudents;
public Student(String name, int UFID, String DOB) {
this.name = name;
this.UFID = UFID;
this.DOB = DOB;
}
public String getDOB() {
return DOB;
}
public void setDOB(String dOB) {
DOB = dOB;
}
public int getUFID() {
return UFID; }
public void setUFID(int uFID) {
UFID = uFID; }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public void setNumberOfStudents(int numberOfStudents) {
Student.numberOfStudents = numberOfStudents;
}
public static void addStudent(String name, int UFID, String DOB) {
numberOfStudents++;
}
public static void dropStudent(String name) {
numberOfStudents--;
}
}
Any guidance as I finish this up would be greatly appreciated.
The assignment writes itself: you need a Roster class that owns and maintains a collection of Students:
public class Roster {
private Set<Student> roster = new HashSet<Student>();
public void addStudent(Student s) { this.roster.add(s); }
public void removeStudent(Student s) { this.roster.remove(s); }
}