Tariq Odeh Tariq Odeh - 7 months ago 10
Java Question

Can I pass user input to my constructor

So I've got the following two classes, I am trying to pass user input into my constructor, thoughts?

import java.util.Scanner;

public class CampingSystem {

public static void main(String[] args) {
NewCamper a = new NewCamper();
Scanner b = new Scanner(System.in);

System.out.println("Input Customer First Name");
String fName = b.nextLine();

System.out.println("Input Customer Surname");
String lName = b.nextLine();


System.out.println(a.getCamperName());

}

}


Then I've also got the class and constructor:

public class NewCamper {
String first;
String last;

public String getCamperName() {
return ( first +" "+ last);
}

NewCamper(){
first = "Ben";
last = "lloyds";
}

}

Answer

Of course you can. You just have to implement a constructor that receives the parameters you want and uses them and then call that contstructor instead. Easy as pie. :-)

NewCamper(String firstName, String lastName){
    first = firstName;
    last = lastName;
}

and

NewCamper a = new NewCamper(fName, lName);