2

我希望这个程序询问用户输入,并创建一个名称等于用户输入的类实例。然后,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();

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

4

2 回答 2

5

看起来您需要一个非默认构造函数:(构造函数不能返回任何值,甚至不能返回 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");
        }
    }
} 
于 2013-11-05T19:08:52.707 回答
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());
}
于 2013-11-05T19:10:49.553 回答