gpt4 book ai didi

java - 在要求我检查值的练习中遇到问题

转载 作者:行者123 更新时间:2023-11-30 04:28:36 25 4
gpt4 key购买 nike

我正在完成 Object 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;
}

}
}

最佳答案

其实这应该是比较容易的。假设您的代码对于删除和检查索引都是正确的,您可以使用 checkindex2 在 if 语句中返回 boolean 值。所以你有

    public void removeFile(int index)
{
if(checkindex2(index))
{
files.remove(index);
}
}

以及列表

    public void listFile(int index)
{
if(checkindex2(index)){
System.out.println(files.get(index));
}
}

关于java - 在要求我检查值的练习中遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15184063/

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