2016-08-30 61 views
-2

下面的類是我的主類。我的數組列表是「員工」的類型,數組列表包含多個對象(多態)的多個元素。所以我想知道,當用戶輸入一個類名時,我應該從數組列表中打印出該類的員工。例如,當用戶輸入「外科醫生」時,程序應該能夠從陣列列表中打印出外科醫生的所有員工。請提前幫助,謝謝。如何從java中的抽象類arraylist打印特定的對象類型

import java.util.*; 


public class HospitalDatabase { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     String q; 
     String w; 
     ArrayList<Employee> e = new ArrayList<Employee>(); 
     Employee s = new Surgeon("Christian Barnard", 2113211, "Cardiac", "Cardiology", 
       2000, "Yale University"); 
     Employee i = new ITSupport("Mickey Mouse", 11280, Department.IT, 26, "Mac OS"); 
     Employee n = new Nurse("Florence Nightingale", 54678, "Urgent Care", 
       "Emergency", false, HospitalWing.North); 
     Employee p = new PatientAccountsManager("Donald Duck", 32465, Department.PatientSupport, 
       99, true); 
     Employee s1 = new Surgeon("Sanjay Gupta", 42171, "Neurosurgery", 
       "Neurology", 500, "Duke University"); 
     Employee n1 = new Nurse("Mary Breckinridge", 56536, "Gynecology", "Midwife", 
       true, HospitalWing.West); 


     e.add(s); 
     e.add(i); 
     e.add(n); 
     e.add(p); 
     e.add(s1); 
     e.add(n1); 

     System.out.println(e.toString()); 
     System.out.println(Employee.numEmployees); 
     System.out.println("-------------******--------------"); 

     Scanner scan = new Scanner(System.in); 
     System.out.println("Enter a name: "); 
     q = scan.nextLine(); 
     boolean j = false; 
     System.out.println("***************"); 

     for(Employee v: e){ 
      if(v.name.contains(q)){ 
       System.out.println(v.name); 
       j = true; 
      } 
     } 
     if(j == false){ 
      System.out.println("Name not found"); 
     } 
     System.out.println("----------------**************---------------"); 

     Scanner f = new Scanner(System.in); 
     System.out.println("Enter the class of employees: "); 
     w = f.nextLine(); 
     System.out.println("***************************"); 

     //PLEASE SHOW THE CODE HERE 
    } 
} 
+2

你會嘗試編碼你的任何問題嗎?對問題進行編碼,但不編碼實際問題在這裏並沒有真正幫助你。 –

+0

您可以嘗試運營商的實例 – Kode

+0

我也希望看到您努力解決此問題。我對於爲其他人編寫代碼不感興趣,特別是當答案真的不是那麼困難的時候。 – markspace

回答

2

您可以使用The Reflection API來執行此操作。 例如:

String className1 = e.getClass().getSimpleName(); 
String className2 = e.getClass().getName(); 
String className3 = e.getClass().getCanonicalName(); 

之所以選擇一個最適合您的考慮this文章。

+0

非常感謝你 – supa

+0

我嘗試過upvote,但我需要很高的聲譽 – supa

+0

只需點擊接受投票buton,請。喜歡在文章:http://meta.stackoverflow.com/questions/251078/how-to-update-and-accept-answers –