Java - 如何从用户输入创建类实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19796730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - How to create a class instance from user input
提问by Gregg1989
I want this program to ask the user for input, and create a class instance with a name equal to the input of the user. Then, the createMember class will create a text file, where all the data of the user will be stored. How do I go about doing it?
我希望这个程序要求用户输入,并创建一个名称等于用户输入的类实例。然后,createMember 类将创建一个文本文件,该文件将存储用户的所有数据。我该怎么做?
Here's the main method:
下面是主要方法:
public static void main(String[] args) {
String input = keyboard.nextLine();
input = new createMember(); // Error. can't do that for some reason?
}
}
Here's the createMember class
这是 createMember 类
public class createMember {
public void setMembership() {
Scanner keyboard = new Scanner(System.in);
out.println("Username: ");
String input = keyboard.nextLine();
try {
//Creates a text file with the same name as the username where data is stored.
Formatter x = new Formatter(input);
} catch (Exception e) {
out.println("Could not create username");
}
}
//Methods for the user
Guys... I know I can simply create an instance like this:
伙计们......我知道我可以简单地创建一个这样的实例:
createMember member = new createMember();
What I actually want to do is HAVE THE USER do that on his own, so the program is flexible and usable for many people. So, based on the input, there will be a separate folder that stores the data for each user.
我真正想做的是让用户自己做,所以这个程序很灵活,对很多人都可用。因此,根据输入,将有一个单独的文件夹来存储每个用户的数据。
采纳答案by azz
Looks like you need a non-default Constructor: (Constructors CANNOT return any value, not even void, as the instance is what is actually returned.
看起来你需要一个非默认的构造函数:(构造函数不能返回任何值,甚至不能返回空值,因为实例是实际返回的。
String input = keyboard.nextLine();
Member m = new Member(input);
public class Member {
private String name;
public Member(String name) {
this.name = name;
}
public void setMembership() {
try {
//Creates a text file with the same name as the username where data is stored.
Formatter x = new Formatter(name);
} catch (Exception e) {
out.println("Could not create username");
}
}
}
回答by Paul Samsotha
You need a constructor
你需要一个构造函数
public class CreateMember {
private String input;
public CreateMember(String input){
this.input = input;
}
public String getInput(){
return input;
}
}
To access the input use CreateMember.getInput()
要访问输入使用 CreateMember.getInput()
public static void main(String[] args){
String input = scanner.nextLine();
CreateMember member = new CreateMember(input);
System.out.println(member.getInput());
}