2016-10-25 22 views
1

我想調用一個具有特定名稱的對象,並將其輸入控制檯。 我知道一種方法將與switch語句,但它也應該與新的初始化對象。請求輸入一個已初始化的對象

這裏是一個代碼示例。

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 

    String nameObject=null; 
    // Create a new Object with a specific name 
    System.out.println("Type in the name of the Object"); 
    try { 
     nameObject = reader.readLine(); 
    } catch (IOException e) { 

    } 
    Person NewPerson = new Person(nameObject); 


    System.out.println("Which Person do you want to have?"); 
String requestName = reader.readLine(); 
//search for the object which has the name requestName 
// after this i want find the right person with an reader.?? 
+0

弄來的nameObject變量什麼價值? – xFighter

+0

是的,我要求提供成爲新對象名稱的人的姓名。初始化工作正常的問題是,當我有幾個人的對象,我想打一個具體的名字。 –

+0

你可以顯示你的Person類嗎? – xFighter

回答

1

好,首先你可以讓你的類,如下所示:

public class Person { 
    public String name; 

    public Person(String name) { 
     this.name = name; 
    } 
} 

然後創建一個Person對象的數組,但你可以使用Person對象的名單:

List<Person> persons = new ArrayList<Person>(); 

然後將創建的人添加到列表中:

persons.add(newPerson); 

,並得到requestName變量後,遍歷列表如下:

for(Person p : persons) { 
    if (p.name.equals(requestName)) { 
     // you got the desired person 
     break; 
    } 
} 
+0

但有了這個,我將不得不爲每個新的初始化對象創建一個if語句。我在討論一個方法,該方法搜索第二個輸出問題後輸入的具有名稱的對象。 –

+0

你能詳細解釋一下嗎? – xFighter

+0

我編輯了我的代碼的最後幾行,我希望它現在會更清晰。 –