我正在完成 Objects First With Java 中的练习(供测试前复习)。一个练习要求我创建一个 checkIndex 方法,我做得正确。下一部分要求我重写我的 listFile 和 removeFile 方法,以便它们使用我的 checkIndex 方法来确保已输入有效参数。我不知道如何做到这一点,并尝试了一些事情。一些帮助将不胜感激。谢谢。
public class MusicOrganizer
{
// An ArrayList for storing the file names of music files.
private ArrayList<String> files;
/**
* Create a MusicOrganizer
*/
public MusicOrganizer()
{
files = new ArrayList<String>();
}
/**
* Add a file to the collection.
* @param filename The file to be added.
*/
public void addFile(String filename)
{
files.add(filename);
}
/**
* Return the number of files in the collection.
* @return The number of files in the collection.
*/
public int getNumberOfFiles()
{
return files.size();
}
/**
* List a file from the collection.
* @param index The index of the file to be listed.
*/
public void listFile(int index)
{
String filename = files.get(index); //not sure
System.out.println(filename);
}
/**
* Remove a file from the collection.
* @param index The index of the file to be removed.
*/
public void removeFile(int index)
{
if(index >= 0 && index < files.size()-1) {
files.remove(index);
}
}
public String getfive(){
return files.get(4);
}
public void addNew(String whatIsYourFavourite){
files.add(whatIsYourFavourite);
}
public void remove(){
files.remove(2);
}
public void checkIndex(int check){
if ((check >= 0) && (check <= files.size()-1)){
}
else{
System.out.println("Valid range must be between 0 and -1");
}
}
public boolean checkIndex2(int check2){
if ((check2 >= 0) && (check2 <= files.size()-1)){
return true;
}
else{
return false;
}
}
}