<Java ArrayList> How to use a different class method for a statement

Asked 2 years ago, Updated 2 years ago, 68 views

package arrayList;

import java.util.ArrayList;

public class Student {

    String name;
    ArrayList<Book> bookList;

    public Student(String name) {
        this.name = name;

        bookList = new ArrayList<Book>();
    }

    public void addBook(String name, int num) {
        Book book = new Book(name, num);
        bookList.add(book);
    }

    public void showStudentInfo() {
        System.out.print(name + "The book that the student read is :");
        For(inti=0; i<book.getNum(); i++) { //This is where the error appears.
            System.out.print(book.getName() +  " " + book.getNum() + " " );
        }
        System.out.println (".");
    }

}

I want to create a program that prints books that students read using ArrayList.

Lee student is land 1, land 2;

Kim student is Taebaek Mountain Range 1, Taebaek Mountain Range 2, Taebaek Mountain Range 3;

Cho students are Harry Potter 1, Harry Potter 2, Harry Potter 3, Harry Potter 4, Harry Potter 5;

I want to use the for statement to get the getNum in the Book class, but I get an error there. I wonder if the variable should be static, if I should put the Book object in the show StudentInfo method, and if I have to, where should I put it?

java arraylist

2022-09-21 12:14

1 Answers

for(int i = 0; i < bookList.size(); i++) { 
    System.out.print(bookList.get(i).getName() +  " " 
        + bookList.get(i).getNum() + " ");
}

The book variable is declared in the addBook function, so it cannot be used only in that function

I think you can take out the books you put on the listYo

But I think the other parts were made well by thinking about the list, but I think you might have mistaken the variable nameYo


2022-09-21 12:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.