2010-02-04 107 views
0

我有以下一段代码: 实际上,方法的数量应该与代码中的相同,我需要从emp_struct类型的对象的链表的元素中提取一个字符串。我该怎么做?Java问题链接列表对象

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; 
    } 
} 
+0

这是一个家庭作业或真实世界的代码? – Jon 2010-02-04 18:00:12

+0

希望这是一项功课..看起来有点凌乱 – Juri 2010-02-04 18:02:22

+4

class emp_struct,认真吗? – GreenieMeanie 2010-02-04 18:04:24

回答

0

在您的搜索方法中,如果您发现该值,则会抛出异常。如果您没有找到该值,则返回true。这似乎不是最好的方法。

如果你发现这个值,你不应该返回true,那么如果它通过该阵列没有找到它,你不应该返回false

+0

同意但功课说你必须使用用户定义异常,所以我被迫这样做,但是我仍然需要从链接列表的指定索引处的对象中提取字符串我的作业的一部分 – manugupt1 2010-02-04 18:12:51

+0

听起来像你想改变你的方法的返回值来返回一个字符串 – bkritzer 2010-02-04 18:23:26

0

此行

Object chkCase = l1.get(begIndex); 

应该

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

除其他事项外...