我想调用一个具有特定名称的Object,我在控制台中输入该名称。 我知道一种方法是使用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 :(得分:1)
好吧,首先,您可以将 Person 类设为以下内容:
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;
}
}