hhel uilop
hhel uilop

Reputation: 1

Calling the Constructor with Scanner

How do you call the constructor that is in another separate class in your main class with Scanner.

Suppose we have

public Person(String personFirstname, String personLastName, String personAddress, String personUsername)
{
    firstName = personFirstName;
    lastName = personLastName;
    address = personAddress;
    username = personUsername;
}

The suppose we have

public class PersonExample
{
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Person dave = new Person();
    }
}

When we want the individual to fill in their own info regarding their name, last name, etc. how can we use the Scanner to have them fill in that info?

Upvotes: 0

Views: 11659

Answers (3)

Scanner c = new Scanner(System.in);
Person p = new Person(c.nextLine(), c.nextLine(), c.nextLine(), c.nextLine());

But this is not a good practice. It is better you validate user inputs first and then create an instance using those values

Upvotes: 0

You need to have some method that knows about both Person and Scanner, and it'll have your logic that reads the appropriate values and sets the fields. My recommendation is to have a static method on Person like this:

public class Person {
    public static Person createFromScanner(final Scanner scanner) {
        String firstName = scanner.next();
        // ...
        return new Person(firstName, lastName, address, username);
    }
}

Then you can call it from somewhere else (like main) like this:

Scanner scan = new Scanner(System.in);
Person dave = Person.createFromScanner(scan);

Upvotes: 0

sandymatt
sandymatt

Reputation: 5612

You need to read that data in using the Scanner

e.g.

Scanner scanner = new Scanner(System.in);

System.out.println("Your name?");
String name = scanner.nextLine();

// ... repeat for all fields ...

Person person = new Person(/*all the fields you just read*/);

Upvotes: 1

Related Questions