Marco Jakob Marco Jakob - 1 month ago 5
Java Question

Request with an input for a initialized Object

I want to call an Object with a specific name which i type into the console.
I know a way would be with a switch statement but it should work also with new initialized Objects.

here is an example of code.

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.??

Answer

well, first you can make your Person class as the following :

public class Person {
    public String name;

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

then create an array of Person objects but you can use list of Person objects :

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

then add the created person into the list:

persons.add(newPerson);

and after getting the requestName variable, iterate through the list, as follows:

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