我正嘗試使用選擇排序來根據shoeId對鞋子進行排序。排序按升序排列。我正在選擇遞歸的方式。我面臨的一個問題是sortShoesRecurse方法。 IT看起來不像我在那裏使用的compareTo方法,但我使用了compareTo方法。選擇根據鞋號升序存儲在陣列中的鞋子的排序
<pre> <code>
if(sc.compare(sh[indexWithMinValue], sh[forwardIndex]) > 0)
</pre> </code>
當我運行程序我收到此錯誤:
<pre> <code>
java.lang.NullPointerException
at shoepkg.ShoeComparator.compare(ShoeComparator.java:8)
//line 8 in the code
// if (obj1.getId() == obj2.getId())
at shoepkg.ShoeProcessor.sortShoesRecurse(ShoeProcessor.java:43)
//if(sc.compare(sh[indexWithMinValue], sh[forwardIndex]) > 0)
at shoetestpkg.TestShoe.main(Shoe.java:28)
//bp.sortShoesRecurse(0);
</pre> </code>
<pre> <code>
public class TestShoe {
public static void main(String[] args) {
ShoeProcessor s = new Shoe();
Shoe s1 = new Shoe(7, "Black");
Shoe s2 = new Shoe(10, "Red");
try {
s.addShoe(s1);
s.addShoe(s2);
}catch(ShoeException bex){
System.out.println("Shoe Exception: " + bex);
}
}
}
public class ShoeProcessor
{
private Shoe [] sh;
private int numShoes=0;
private ShoeComparator<Shoe> sc;
public ShoeProcessor()
{
sh = new Shoe [10];
sc=new ShoeComparator<Shoe>();
}
public void addShoe(Shoe s) throws ShoeException
{
if(s.getId() < 0) {
throw new ShoeException(s);
}
else {
if(numShoes<10){
sh[numShoes]=s;
numShoes++;
}
}
}
public void sortShoesRecurse(int startIndex)
{
if (startIndex >= sh.length - 1) {
return;
}
int indexWithMinValue=startIndex;
for(int forwardIndex=startIndex+1; forwardIndex<sh.length;forwardIndex++) {
if(sc.compare(sh[indexWithMinValue], sh[forwardIndex]) > 0) {
indexWithMinValue = forwardIndex;
}
}
Shoe temp= sh[startIndex];
sh[startIndex]=sh[indexWithMinValue];
sh[indexWithMinValue]= temp;
sortShoesRecurse(startIndex+1);
}
public Book[] getBooks() {
return books;
}
}
package shoepkg;
public class ShoeComparator<T extends Shoe>
{
public int compare(T obj1, T obj2)
{
if (obj1.getId()== obj2.getId())
{
return 0;
}
if (obj1.getId() > obj2.getId())
{
return 1;
}
else if (obj1.getId() < obj2.getId())
{
return -1;
}
return 0;
}
}
</pre> </code>
我做了一些更新,提出了一些建議後的代碼,這是當前的代碼。仍然得到一些錯誤,這些錯誤也在頂部進行了更新。感謝您的幫助。我不得不根據Id來比較對象。
我更新了我的主帖。我需要使用兩個對象進行比較,並需要根據它們的ID進行比較。 – user1282256