简体   繁体   中英

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";
    }

}

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);

Sure thing! Create a constructor

public NewCamper(String first, String last) {
    this.first = first;
    this.last = last;
}

Then in CampingSystem

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();

NewCamper a = newCamper(fName, lName);

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

In your NewCamper class, build a constructor that receives the parameters that you want

public class NewCamper {
    String first;
    String last;

    public newCamper(String firstName, String lastName) {
        this.first = firstName;
        this.last = lastName;
    }

    public NewCamper() {
        first = "Ben";
        last = "lloyds";
    }
    public String getCamperName() {
        return ( first +" "+ last);
    }
}

Then, in your Camping System class, call that constructor with the code:

NewCamper person = new NewCamper(fname,lname);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM