所以我有以下两个类,我试图将用户输入传递给我的构造函数,想法?
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());
}
}
然后我也得到了类和构造函数:
public class NewCamper {
String first;
String last;
public String getCamperName() {
return ( first +" "+ last);
}
NewCamper(){
first = "Ben";
last = "lloyds";
}
}
答案 0 :(得分:2)
当然可以。您只需实现一个接收所需参数的构造函数并使用它们,然后调用该contstructor。非常简单。 : - )
NewCamper(String firstName, String lastName){
first = firstName;
last = lastName;
}
和
NewCamper a = new NewCamper(fName, lName);
答案 1 :(得分:0)
当然可以!创建一个构造函数
public NewCamper(String first, String last) {
this.first = first;
this.last = last;
}
然后在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());
答案 2 :(得分:0)
在NewCamper类中,构建一个接收所需参数的构造函数
imggif
然后,在您的Camping System类中,使用代码
调用该构造函数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);
}
}