2010-02-04 109 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); 

除其他事項外...