【问题标题】:How would I take user input and add it into an arraylist?我将如何获取用户输入并将其添加到数组列表中?
【发布时间】:2014-03-06 07:01:26
【问题描述】:

我目前编写了一个名为 PostTUI 的类,我需要知道是否可以将人们从我的扫描仪中写入的输入添加到我的数组列表中。

public class PostTUI {

    private Scanner scan = new Scanner(System.in);
    private PostManager manager;
    private String userChoice;
    private String author;
    private String message;

    public PostTUI(PostManager manager) {
        this.manager = new PostManager();
    }
    public void run() {
        System.out.println("1 - Create a new Message Post");
        System.out.println("2 - Create a new Photo Post");
        System.out.println("3 - Create a new Event Post");
        this.userChoice = this.scan.nextLine();

        if (this.userChoice.equals("1")) {
            System.out.println("Who is the author?");
            this.author = this.scan.nextLine();
            System.out.println("What is the message?");
            this.message = scan.nextLine();
            this.manager.addPost(Post newPost);
        }

    }
}

PostManager 类是声明和初始化数组列表的类。它有一个接受和存储帖子的方法(addPost)和一个 toString 方法。

【问题讨论】:

  • 最后一行代码不起作用,所以我假设我做错了什么。

标签: java arraylist user-input


【解决方案1】:

您还没有明确说明在哪里使用ArrayList,但大概在PostManager 内部,并且您使用add() 方法添加到它。无论如何,这不是您创建新对象的方式,这就是最后一行给您错误消息的原因。你想要这个:

this.manager.addPost(new Post());

您尚未向我们展示Post 类,但也许您想将作者和消息Strings 作为参数传递给Post 构造函数?

【讨论】:

  • 我对从 post 继承的每个消息、照片和事件帖子类都有继承。我需要做的就是你所说的,除了将 Post() 更改为 this.manager.addPost(new MessagePost(author, message));它奏效了。谢谢大佬!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多