I have two classes. Student and StudentTest.
My test class wil read the student info from the command line. I also need to check if the student already exists with equals() method. Can someone help me with this?

Student

public class Student { 
         
private String firstName; 
private String lastName; 
private String studentNumber; 
 
     
        Student(String fName,String lName,String sNumber)  
        { 
                firstName=fName;   
                lastName=lName;   
                studentNumber=sNumber; 
                 
        }  
         
        public Student() 
        { 
         
        } 
 
        public void setFirstName(String fName) 
        { 
        firstName=fName;   
        }  
         
        public String getFirstName()   
        { 
                return firstName; 
                 
        }
         
        public void setLastName(String lName)   
        { 
        lastName=lName
        } 
         
        public String getLastName()  
        { 
                return lastName;       
        } 
         
        public void setStudentNumber(String sNumber)   
        { 
        studentNumber=sNumber;    
                 
        }         public String getStudentNumber() 
        { 
        return studentNumber; 
                 
        } 
          
        public String toString()         { 
                return String.format("%-8s %-9s %-8s\n",firstName,lastName,studentNumber ); 
        }
}
//StudentTest
import java.util.Scanner;

public class StudentTest {
	public static void main( String[] args)
	{   
		Student[] students = new Student[2];
		Scanner inputs = new Scanner(System.in);
		for(int i = 0 ; i < students.length; i++)
	    { 
	       
	      System.out.println("Please enter Student Number");
	      String fName = inputs.nextLine(); 
	      System.out.println("Please enter Student First Name");
	      String lName = inputs.nextLine(); 
	      System.out.println("Please enter Student Last Name");
	      String sNumber = inputs.nextLine(); 
	      students[i] = new Student(fName, lName, sNumber);
	    
	    
	}
		for(int i = 0 ; i < students.length; i++)
	    { 
		System.out.print(students[i].toString());
	}
	

}
}

Dani AI

Generated

A few concrete, low-friction things to make the “already exists” check reliable.

First, decide what defines a Student’s identity (usually a unique student number). Then override equals(Object) and hashCode() in Student so collections and contains/add behave correctly (they must be consistent). This also lets you use List.contains or a Set to detect duplicates instead of writing your own indexOf. ’s indexOf idea is fine, and was right to warn about nulls — never call equals on a possibly-null element.

Example equals/hashCode that treats studentNumber as the unique key:

@Override
public boolean equals(Object obj) {
    if (this == obj) return true;
    if (obj == null || getClass() != obj.getClass()) return false;
    Student other = (Student) obj;
    if (studentNumber == null) return other.studentNumber == null;
    return studentNumber.equals(other.studentNumber);
}

@Override
public int hashCode() {
    return studentNumber == null ? 0 : studentNumber.hashCode();
}

In your test code prefer a List or Set so duplicate detection is simple. For example, use ArrayList and contains (linear) or HashSet for O(1) checks:

List<Student> students = new ArrayList<>();
// read sNumber, fName, lName in the correct order
Student s = new Student(fName, lName, sNumber);
if (students.contains(s)) {
    System.out.println("Student already exists");
} else {
    students.add(s);
}

Quick troubleshooting notes tied to the thread: pointed to best-practice reading on equals/hashCode — follow that. Fix the minor bugs in your posted code (the setter for lastName is missing a semicolon, and the input prompts/variable assignments are mismatched). If you use a HashSet, remember both equals and hashCode must be overridden.

Recommended Answers

All 7 Replies

You need to clarify what you want better and specify the place in the code where you are having an issue. However, this might help you:

Student s;

/* ...More lines of code here... -- s may have been initialized or it may still be an empty pointer */

if (s==null) //if the pointer is not pointing to an existing object
    s = new Student(); //create a new object and assign the pointer to it

I would suggest to write a method that takes as arguments the array of Students and a Student object:

boolean static int indexOf(Strudent [] array, Strudent st) {
  
}

Loop the array and see if the array contains the Student st. If found, immediately return the index where that student is. If you finish the loop without returning, means that you didn't found the student, so return -1 at the end:

YOUR Code with mine:

//StudentTest
import java.util.Scanner;

public class StudentTest {
	public static void main( String[] args)
	{   
		Student[] students = new Student[2];
		Scanner inputs = new Scanner(System.in);
		for(int i = 0 ; i < students.length; i++)
	    { 
	       
	      System.out.println("Please enter Student Number");
	      String fName = inputs.nextLine(); 
	      System.out.println("Please enter Student First Name");
	      String lName = inputs.nextLine(); 
	      System.out.println("Please enter Student Last Name");
	      String sNumber = inputs.nextLine(); 
 
//        NEW CODE ///////////////
               Student st = new Student(fName, lName, sNumber);

               if (indexOf(students, st)==-1) {
                   // New Student
	           students[i] = new Student(fName, lName, sNumber);                    
              } else {
                    System.out.println("Student: "+st+", already exists");
                    i--;
              }
//        NEW CODE ///////////////

	}
		for(int i = 0 ; i < students.length; i++)
	    { 
		System.out.print(students[i].toString());
	}
	

}

boolean static int indexOf(Strudent [] array, Strudent st) {
    // TODO
}

}

Be careful in that method to make sure that you don't compare any null objects. The array when initialized has null values as elements, so I would suggest something like this: st.equals(array[i]); instead of array[i].equals(st); Also for the above comparison you must use the equals method. For that you will need to override it in the Student class, like you did the toString method.

And you don't need this: System.out.print(students[i].toString()); When you call this: System.out.print(students[i]); The toString method is automatically called. That is the purpose of overriding that method in the first place: System.out.println("Student: "+st+", already exists"); At the previous example the toString is also automatically called.

Ok this is serious and somebody should do something about it. I just saw that need, the poster who created this thread got down voted, twice!

I would like the @#!@$!@$# that did this to post here and explain the reasons. Because people get down voted for no reasons when they have very good posts, or posts that violate no rules, such as this one.

Why was the fist post down voted?? Are you man enough to show yourself and explain why?

It's actually quite ridiculous my code snippet got voted down twice the other day also -- I think it's just incompetent users randomly voting things down they don't immediately understand because they are java noobs. I don't think it's something to really worry about. And... I'm guessing this post will be voted down too ;)

It's actually quite ridiculous my code snippet got voted down twice the other day also -- I think it's just incompetent users randomly voting things down they don't immediately understand because they are java noobs. I don't think it's something to really worry about. And... I'm guessing this post will be voted down too ;)

I don't believe it is because they don't understand the code, but simply because they are just bad and mean. But I will have to agree with the randomness thing.

Also since this is getting way out of topic I suggest we stop here discussing about it. At the DaniWeb Community Feedback forum there is a thread there you can contribute.

Well, the tooltip for the down-vote arrow merely says "This post is unclear", so the down-voters may have simply thought it was a poorly structured question or that he should have been more specific about what he was having trouble with.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.