1

I have written an employee class which has a display method and the constructor.

public class employee {
public int empid;
public String name;

public employee(int id, String name){
empid = id;
this.name = name;
}

public void display (){
System.out.println("Employee id: " +empid +"\nEmployee name: "+name);
}
}

I then created three objects of employee and stored them in an array in the main class. I created an if block which will check user guess and print the employee details if he exists or will throw an exception if the data is not present. The if block was enclosed in an enhanced for loop which loops through the array.

public static void main(String[] args) {
    // TODO code application logic here


employee priya = new employee (001, "Priya");
employee tamizh = new employee (002, "Tamizh");
employee hari = new employee (003, "hari");

employee[] list = new employee[3];
list[0] = priya;  
list[1] = tamizh;
list[2] = hari;



int userGuess = 002;

for (employee l : list){

    if (userGuess == l.empid)
    {
    l.display();
    break;
    }
    else
    {
    throw new InputMismatchException ("employee doesnot exist");
    }
}
}   
}

The trouble is that the program throws the exception even if the guess is correct. I tried the int variable empid and then the String variable name, but both the == and .equals didn't work. I searched stackoverflow and the solution suggested was to override the hashcode and equals method in the employee class. I did that.

public class employee {
public int empid;
public String name;
public employee(int id, String name){
empid = id;
this.name = name;
}

public void display (){
System.out.println("Employee id: " +empid +"\nEmployee name: "+name);
}
    @Override
    public int hashCode(){
    final int prime = 31;
    int result = 1;
    result = prime * result + empid;
    result = prime * result + name.hashCode();
    return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        employee other = (employee) obj;
        if (this.empid != other.empid)
            return false;
        if (this.name.equals(other.name))
            return false;
        return true;
    }       
}

Now when I give the input as 001, the code works fine. But for any other input (including the existing empids 002 and 003), the exception is being thrown.

What had I done wrong in the overriding? Also I don't understand the code I had written to override the two methods. Can someone explain the logic and where I went wrong? Thanks.

Edit: Thanks guys. I have realized my mistake in the for loop and I have edited it. It works perfectly now.

int userGuess = 002;
boolean found = false; 
for (employee l : list){

    if (userGuess == l.empid)
    {
    l.display();
    found = true;
    break;
    }
}
if(found == false){
    try{
    throw new InputMismatchException ("employee doesnot exist");
        }
    catch(InputMismatchException e){
     System.out.println("Employee doesnot exist.");
    }
}

Thanks a lot guys. Can someone explain what I have done in equals and hashcode methods? I copied the code from an answer and I couldn't find an explanation for it. Thanks again.

12
  • The first in the array is 001 so of course it's not equal to 002. Not sure what you are trying to do. you are not using the equals method here. Commented Dec 12, 2017 at 16:12
  • 1
    You throw the exception in loop, and you didn't catch it. so it didn't comes to loop for second time. Commented Dec 12, 2017 at 16:19
  • @puterBoy If you explain the issue with my answer, I can try to correct it. Thanks, Commented Dec 12, 2017 at 16:40
  • @isaace I tried your code and the program still exited the if block and threw the exception after the first iteration. The exception needed to be taken outside the for loop to make the code work. Commented Dec 12, 2017 at 16:45
  • It is outside of the for loop in my answer. I don't see how it's possible that it exited after the first iteration.. Commented Dec 12, 2017 at 16:47

2 Answers 2

1

You iterate through your whole array starting at the first entry. So if you compare the first entry with your user input (lets say its 002) the statement will be false. So it will throw an exception.

To solve this issue you would have to check if an entry has been found AFTER iterating through your array.

int userGuess = 002;
boolean userFound = false;
for (employee l : list)
{
    if (userGuess == l.empid)
    {
       userFound = true;
       l.display();
       break;
    }
}

if(!userFound)
{
   throw new InputMismatchException ("employee doesnot exist");
}

To answer your second question:

i dont think you'll need the equals() and hashCode() method.

The equals checks if two objects are the same (see https://msdn.microsoft.com/de-de/library/bsc2ak47(v=vs.110).aspx)

the hashCode() method generates a "unique" value for an object (see https://msdn.microsoft.com/de-de/library/system.object.gethashcode(v=vs.110).aspx)

Sign up to request clarification or add additional context in comments.

Comments

0

This should work for you:

boolean found = false;
for (employee l : list){
  if (userGuess == l.empid) {
      l.display();
       found = true;
        break;
    }
}
if(!found){
    throw new InputMismatchException ("employee doesnot exist");
}

Your existing code will not work because the first in the loop is always 001.

4 Comments

This won't tell which employee is not exist.
@Truthira OP is talking about manual input. Please read carefully the question.
From OP "I created an if block which will check user guess and print the employee details if he exists or will throw an exception if the data is not present. " I think op accepted yours earlier, btw i din't downvote you :)
@Truthira I didn't think you downvoted. It looks like the OP is hardcoding an id. If the OP would comment here I'll know why they unaccepted it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.