[英]How would I take user input and add it into an arraylist?
I have currently written a class called PostTUI and I need to know if I could take the input people write from my scanner and add it into my arraylist. 目前,我已经编写了一个名为PostTUI的类,我想知道我是否可以接受人们从扫描仪中写入的输入并将其添加到我的arraylist中。
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);
}
}
}
The PostManager class is the class who's job it is to declare and initialize the arraylist. PostManager类是声明和初始化arraylist的工作类。 It has a method that accepts and stores a post (addPost) and a toString method. 它具有接受和存储帖子(addPost)和toString方法的方法。
You haven't made it explicitly clear where you use an ArrayList
, but presumably inside the PostManager
and you add to it with the add()
method. 您尚未明确说明使用ArrayList
,但大概是在PostManager
内,并使用add()
方法添加到其中。 In any case, that's not how you create a new object, which is why the last line is giving you an error message. 无论如何,这不是您创建新对象的方式,这就是为什么最后一行会向您显示错误消息的原因。 You want this instead: 您想要这个:
this.manager.addPost(new Post());
You haven't shown us the Post
class, but maybe you want to pass the author and message String
s as arguments to the Post
constructor? 您尚未向我们展示Post
类,但是也许您想将author和消息String
作为参数传递给Post
构造函数?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.