謝罪これは愚かな質問であれば、私はプログラミングが比較的新しいです。海によって送信された空気により、送信済みアイテム、およびアイテム: プリミティブデータ型のためのComparableインターフェイスの使用
は基本的に私は2つのアイテムの種類をサポートしている郵便局のシナリオを作成するために、宿題の質問を持っていました。それぞれのタイプについて、私はcalcFeeメソッドを使って総配送コストを計算しました。宿題の第2の部分は、それがアイテムは、そのcalcFee値でソートされている同等のインタフェースを実装するようにアイテム・クラスを拡張するために尋ねます。今私は、プリミティブなデータ型をComparableインターフェイスからソートすることはできないことを理解しています。問題は、特に私が何か間違ったことをやっているComparableインタフェースを使用するか、私は任意の助けをいただければ幸い誤っ
プログラムを作成していますするように求められますので。
package homework3;
import java.util.ArrayList;
import java.util.Collections;
/**
*
* @author Josh
*/
public class Homework3 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<Item> items = new ArrayList();
items.add(new airItems(11, "josh", "sam", 295));
items.add(new airItems(11, "zosh", "sam", 295));
items.add(new seaItems(11, "aosh", "sam", 11, 12, 15));
Collections.sort(items);
for (Item i : items){
i.calcFee();
i.print();
}
}
}
class Item implements Comparable<Item>{
int id;
String from;
String to;
double fee;
public Item(int id, String from, String to){
this.id = id;
this.from = from;
this.to = to;
}
public void print(){
System.out.println("id: " + id + "\tFrom: " + from + "\tTo: " + to + "\tFee: " + fee);
}
public double calcFee(){
return 0;
}
@Override
public int compareTo (Item item1){
return this.fee.compareTo(item1.calcFee());
}
}
class airItems extends Item{
long weight;
public airItems(int id, String from, String to, int weight){
super(id, from, to);
this.weight = weight;
}
public void print(){
super.print();
System.out.println("Weight: " + weight);
System.out.println("");
}
@Override
public double calcFee(){
if (weight < 100){
fee = 2.5;
}
else if (weight < 200) {
fee = 5;
}
else if (weight < 300) {
fee = 7.5;
}
return fee;
}
}
class seaItems extends Item{
int length;
int width;
int depth;
public seaItems(int id, String from, String to, int length, int width, int depth){
super(id, from, to);
this.length = length;
this.width = width;
this.depth = depth;
}
@Override
public double calcFee(){
if (length <= 10 && width <= 10 && depth <= 10){
fee = 5;
}
else if (length <= 20 && width <= 20 && depth <= 20){
fee = 10;
}
if (length <= 50 && width <= 50 && depth <= 50){
fee = 5;
}
else if (length > 50 && width > 50 && depth > 50){
fee = 0;
}
return fee;
}
@Override
public void print(){
super.print();
System.out.println("Length: " + length + "\tWidth:" + width + "\tdepth" + depth);
System.out.println("");
}
}
どこにでも実装されている「Comparable」インターフェイスは表示されません。まだ何か試しましたか? –
プリミティブデータ型で 'Comparable'を使用していないので、' Item'クラスでそれを使用しています。あなたの 'Item'クラスは' Comparable'を拡張し、 'compareTo'メソッドを実装して、各' Item'の 'calcFee'値を比較する必要があります。 – Vikram
申し訳ありませんが、私はエラーを引き起こしたので、比較可能なインターフェイスを使用しようとしました。私の試みを含めるためにコードを編集したので、上記のコードを参照してください。これは、基本的にcompareToメソッドに "doubleは参照解除できません"というエラーを表示します。 上記の同じメソッドを使用してStringをソートできます。ブール値をソートしようとするとエラーになります。 – Josh