Java - 如何从用户输入创建类实例

时间:2013-11-05 19:03:24

标签: java class instance java.util.scanner

我希望这个程序向用户询问输入,并创建一个名称等于用户输入的类实例。然后,createMember类将创建一个文本文件,其中将存储用户的所有数据。我该怎么做呢?

这是主要方法:

     public static void main(String[] args) {

         String input = keyboard.nextLine();        
         input = new createMember(); // Error. can't do that for some reason?
    }
}

这是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

伙计们...我知道我可以简单地创建一个这样的实例:

  createMember member = new createMember();

我真正想做的是让用户自己做,所以该程序灵活,可用于许多人。因此,根据输入,将有一个单独的文件夹存储每个用户的数据。

2 个答案:

答案 0 :(得分:4)

看起来你需要一个非默认的构造函数:(构造函数不能返回任何值,甚至不能返回void,因为实例是实际返回的。

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

答案 1 :(得分:1)

你需要一个构造函数

public class CreateMember {
    private String input;

    public CreateMember(String input){
        this.input = input;
    }

    public String getInput(){
        return input;
    }
}

要使用CreateMember.getInput()

访问输入
public static void main(String[] args){
    String input = scanner.nextLine();
    CreateMember member = new CreateMember(input);

    System.out.println(member.getInput());
}