user3241721
user3241721

Reputation: 143

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.

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. It has a method that accepts and stores a post (addPost) and a toString method.

Upvotes: 0

Views: 88

Answers (1)

Martin Dinov
Martin Dinov

Reputation: 8815

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. 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 Strings as arguments to the Post constructor?

Upvotes: 1

Related Questions