【发布时间】:2017-03-04 08:07:09
【问题描述】:
所以我正在为我的 CS 课程编写代码,它要求我使用二进制搜索。
但是,每当我运行代码时,都会收到一条错误消息,指出 this
这是说我的二进制搜索有问题,但我不知道为什么。
如果你需要我,我可以发布我制作的其他 2 个课程,但我真的很困惑为什么它没有通过。
我觉得我的发音或搜索调用是一个愚蠢的错误。 提前感谢朋友们。
编辑: 如果它对您有更好的帮助,这是对代码的要求。
修改电影程序,使其保持按导演排序的 DVD。为了产生有效的代码,不要应用排序来保持 DVD 的排序。 改用重新设计方法添加,以便将 DVD 插入排序集合并生成排序集合。 此外,实施一种有效的方法来搜索导演给定的 DVD。方法应称为 searchForDVD。它应该只有字符串类型的形式参数,提供我们正在搜索的导向器。返回类型应该是一个整数,它指定 DVD 所在数组中的索引。当搜索不成功时,方法返回 -1。方法 searchForDVD 应该在 DVD 集合类中。 修改 main 方法,以便最后它还通过执行一次成功和一次不成功的搜索来测试方法 searchForDVD。 显示在成功搜索中找到的 DVD,否则请写上适当的评论。
程序运行大纲:
显示所有 DVD
再添加两张 DVD
添加这两张 DVD 后显示所有 DVD
搜索收藏中的特定 DVD 并显示它
搜索不在收藏中的特定 DVD
这是这一类的完整代码。
import java.util.*;
public class DVDCollection
{
private DVD[] collection;
private double totalCost;
public DVDCollection()
{
collection = new DVD[100];
totalCost = 0.0;
}
public void addDVD(String title, String director, int year, double cost, boolean bluray)
{
DVD newDvd = new DVD(title, director, year, cost, bluray);
int index = Collections.binarySearch(collection, newDvd);
if(index >= 0) {
System.out.println("DVD with title " + newDvd.getTitle() + " already exists.");
}
else {
int index1 = -index - 1;
collection = insertDVD(collection, newDVD, index1);
System.out.println("DVD with title " + newDvd.getTitle() + " added.");
}
totalCost += cost;
}
private DVD[] insertDVD(DVD[] original, DVD newDVD, int in)
{
int length = original.length;
DVD[] destination = new DVD[length+1];
System.arraycopy(original, 0, destination, 0, in);
destination[in] = newDVD;
System.arraycopy(original, in, destination, in+1, length-in);
return destination;
}
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
report += "My DVD Collection\n\n";
report += "Number of DVDs: " + count + "\n";
report +="Total cost: " + fmt.format(totalCost) + "\n";
report += "Average cost: " + fmt.format(totalCost/count);
report += "\n\nDVD List: \n\n";
for (int dvd = 0; dvd < count; dvd++)
report += collection[dvd].toString() + "\n";
return report;
}
}
【问题讨论】:
-
在您的问题中包含错误消息。
-
你用静态方法
binarySearch写了一个类Collections吗?
标签: java binary-search