Input already created object via Scanner and do something with it

Viewed 31

I want to know if it is possible to write an object name in an input(Scanner or maybe another way?) through the console and then do something with it.

package test;
import java.util.ArrayList;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
    
        Scanner input = new Scanner(System.in);
    
        Person p1 = new Person(1, "pedro");
        Person p2 = new Person(2, "juan");
        Person p3 = new Person(3, "diego");
    
        ArrayList personList = new ArrayList();
        personList.add(p1);
        personList.add(p2);
    
        //Something like this doesn't work :S
        Person personToAdd = input.nextPerson();
        personList.add(personToAdd);
    
    
    }

}

for example in this case I wanna input the object name "p3" and then add it to the ArrayList, is there any way to do something like this?

1 Answers
List<Person> personList = new ArrayList<Person>();
personList.add(p1);
personList.add(p2);

// you need to get each field you want to save with scanner
// nextLine/nextInt and so on to set other field
// e.q newPerson.setAge(<value from scanner>)
String personName = input.nexLine();
Person newPerson = new Person(personName);
personList.add(newPerson);
Related