gpt4 book ai didi

java - 从 main 中的另一个类方法调用数组

转载 作者:行者123 更新时间:2023-12-02 01:44:12 25 4
gpt4 key购买 nike

为了将代码保存在主空间中,我在另一个类方法中编写了一些业余代码,我想将其实现到我的主方法中。但是,每当我在为该类创建对象后尝试调用该方法时,都会收到一条错误消息。您能启发我并告诉我我做错了什么吗?

这是我在数组类中编写的代码。

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);
}

这是主代码:

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

错误消息:

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

最佳答案

如果类 ListBook 有一个 String 数组,它应该是一个属性,那么当您调用 printList() 时,您'将读取这个数组。因为现在的问题是数组与实例相关,不应该作为参数传递

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);
}
}
}

并用作

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();
}

关于java - 从 main 中的另一个类方法调用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53948381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com