views:

177

answers:

2

I have the following piece of code : Essentially the number of methods should remain the same as in the code and I need to extract a string from an element of the linkedlist of Objects of type emp_struct.. How do I do it?

import java.util.*;
import java.io.*;

class a1 {

    static LinkedList l1;
    private emp_struct input() throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        emp_struct obj = new emp_struct();
        obj.emp_id = br.readLine();
        obj.name =  br.readLine();
        obj.salary = Double.parseDouble(br.readLine());
        obj.dept = br.readLine();
        try{
            search(obj);
        }catch(Exception e){
            System.out.println(e);
            obj = input();
        }
        return obj;

    }

    boolean search(emp_struct obj)
    {
        int lastIndex = l1.lastIndexOf(l1);
        int begIndex = 0;
        for(begIndex =0;begIndex<lastIndex;begIndex++)
        {
            Object chkCase = l1.get(begIndex);
            String chk = chkCase.getEmpID();
            if(chk.equals(obj.emp_id));
                throw new DuplicateEntryException("Duplicate entry found");

        }           
        return true;
    }
    public static void main(String args[]) throws IOException
    {
        l1 = new LinkedList();
    }
}

class DuplicateEntryException extends Exception {
    String detail;
    DuplicateEntryException(String a)
    {
        detail = a;
    }

    public String toString()
    {
        return "User Defined Exception : "+detail;
    }
}

class emp_struct {
    public String emp_id;
    public String name;
    public double salary;
    public String dept;

    public String getEmpID()
    {
        return emp_id;
    }

    public String toString()
    {
        return emp_id+"\t"+name+"\t"+salary+"\t"+dept;
    }
}
A: 

In your search method, if you find the value, you're throwing an exception. If you don't find the value, you return true. This doesn't seem like the best approach.

If you find the value, shouldn't you return true, then if it makes it through the array without finding it, shouldn't you return false?

bkritzer
agreed but the homework says u have to use a user defind exception so i was forced to do it that way however I still need to extract the string from the object at specified index of the linked list which is not part of my homework
manugupt1
Sounds like you want to change the return value of your method to return a String
bkritzer
A: 

This line

Object chkCase = l1.get(begIndex);

should be

emp_struct chkCase = (emp_struct)l1.get(begIndex);  

among other things...

rodrigoap