带有初始化对象输入的请求
Request with an input for a initialized 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.??
嗯,首先你可以让你的 Person class 如下:
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;
}
}
我想调用一个具有我在控制台中键入的特定名称的对象。 我知道一种方法是使用 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.??
嗯,首先你可以让你的 Person class 如下:
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;
}
}