简体   繁体   中英

Calling array from another class method in main

To save code in the main space I've written some amateurish code in another class method, which i want to implement into my main method. However, I'm getting an error message whenever I try to call the method after creating the object for that class. Could you please enlighten me and tell me what I'm doing wrong?

This is the code that I've written in the array class.

public ListBook() {
    String[]bookList= new String[11];
    bookList[0]="Necromonicon";
    bookList[1]="The Hobbit";
    bookList[2]="Hannibal";
    bookList[3]="Cooking an egg";
    bookList[4]="The Hulk smashes again";
    bookList[5]="The Tyranny of a king";
    bookList[6]="The Phantom Menace";
    bookList[7]="Rogue One: A Starwars Story";
    bookList[8]="The Mighty Hercules";
    bookList[9]="The Serpents Gaze";
    bookList[10]="The End of the World";    
    }


public void printList(String bookList[]) {
    for(String x:bookList) {
    System.out.println(x);
}

And this is the code from the main:

public static void main(String[] args) {
    ListBook r = new ListBook();
    r.printList();
}

Error message:

The method printList(String[]) in the type ListBook is not applicable for the arguments()

If the class ListBook has an array of String is should be an attribute, then when you'll call printList() you'll read this array. Because the problem now is that the array is related to an instance and should not be passed as parameter

public class ListBook {

    private static String[] defaultBooks = {"Necromonicon", "The Hobbit", "Hannibal", "Cooking an egg", "The Hulk smashes again", "The Tyranny of a king",
            "The Phantom Menace", "Rogue One: A Starwars Story", "The Mighty Hercules", "The Serpents Gaze", "The End of the World"};

    private String[] bookList;

    public ListBook() {
        this(defaultBooks);
    }

    public ListBook(String[] books) {
        bookList = books;
    }

    public void printList() {
        for (String x : bookList) {
            System.out.println(x);
        }
    }
}

And use as

public static void main(String[] args) {
    ListBook r = new ListBook();
    r.printList();
    // OR
    ListBook r2 = new ListBook(new String[]{"Book 1", "Book 2", "Book 3"});
    r2.printList();
}

You are not passing any argument to your method call. Change your method to this if what you want is to use the list in your class

public void printList() {
    for(String x:bookList) {
    System.out.println(x);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM