自定义的数组自定义方法的Java对象 [英] Custom Methods for an Array of Custom Objects in Java
问题描述
我试图创建类型图书馆
,在那里我可以存储类型图书馆
的许多对象的数组我稍后会管理。之前,我太深,我试图让打印()
方法在阵列上,这样我可以简单地调用 myLibrary.print()
打印阵列。
I am trying to create an array of type Library
, where I can store many objects of type Library
that I'll manage later. Before I get too deep, I am trying to make a print()
method on the array so that I can simply call myLibrary.print()
to print the array.
public class Library {
// Constructor
public Library() {
}
public void print() {
System.out.println("Library Sorted by Title");
}
}
public class MediaManager {
public static void main(String[] args) throws Exception {
Library myLibrary[] = new Library[100];
myLibrary.print();
}
}
我收到一个错误说没有打印()
在库[]
。
我将如何去打印此阵?我只是通过数组循环中的主文件,并会调用每个对象单独的打印?如果是这种情况,在那里我会编写自定义的方法来对数组进行排序?
How would I go about printing this array? Would I just loop through the array in the main file and call a separate print on each object? If this is the case, where would I write custom methods to sort the array?
更新
从我的任务要求:
您的程序将使用类型库的一个阵列,用于存储从输入文件中读出所有的信息。
Requirements from my assignment: "Your program will use one array of type Library to store all information read from the input file."
在顶层,你将有一个名为Library类图书馆将有三个子类:。音乐,图书和电影音乐将有两个子类:歌曲和专辑书将有两个子类:小说和非小说电影,小说,非小说,乐曲和专辑不会有任何的子类。
"At the top level you will have a class called Library. Library will have three subclasses: Music, Book, and Movie. Music will have two subclasses: Song and Album. Book will have two subclasses: Fiction and Nonfiction. Movie, Fiction, Nonfiction, Song, and Album will not have any subclasses."
更新2
这是一个CS-101课程。我不觉得我应该需要使用具有可比性。
This is for a CS-101 course. I don't feel I should need to use Comparable.
推荐答案
在除了定义打印()
方法图书馆
;您可以尝试以下操作:
In addition to defining print()
method for Library
; You can try following:
public void printLibrary (Library [] libraryArray) {
for(Library library : libraryArray)
library.print();
}
或者如果你超载的toString()
为图书馆
您可以简单地使用:
public void printLibrary (Library [] libraryArray) {
for(Library library : libraryArray)
System.out.println(library);
}
和调用将像做:
Library myLibrary[] = new Library[100];
printLibrary(myLibrary);
编辑:
要你应该实现可比&LT数组排序;图书馆与GT;
在图书馆
类,并简单地用
To sort the array you should implement Comparable<Library>
in Library
class and simply use
Arrays.sort(myLibrary);
对数组排序。
这篇关于自定义的数组自定义方法的Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!