为啥报错了

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

3回答
irista23 2018-12-05 13:37:09

我这里运行你的代码可以正常输出

http://img1.sycdn.imooc.com//climg/5c0763d30001a89b07090687.jpg

提问者 乃好 2018-12-05 12:52:07
//Goods类
public class Goods implements Comparable<Goods> {

	@Override
	public int compareTo(Goods o) {
		//取出商品价格
		double price1 = this.getPrice();
		double price2 = o.getPrice();
		int n = new Double(price2-price1).intValue();
		return n;
	}
	private String id;
	private String name;
	private double price;
	public Goods() {
		super();
	}
	public Goods(String id, String name, double price) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	@Override
	public String toString() {
		return "商品编号:" + id + ", 商品名称:" + name + ", 商品价格:" + price;
	}
	
}

===================================

//GoodsTest类

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.imooc.set.Goods;

public class GoodsTest1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Goods g1 = new Goods("s0001","手机",2000);
		Goods g2 = new Goods("s0002","冰箱",1000);
		Goods g3 = new Goods("s0003","电视机",3000);
		List<Goods> goodsList = new ArrayList<Goods>();
		goodsList.add(g1);
		goodsList.add(g2);
		goodsList.add(g3);
		
		//排序前
		System.out.println("排序前:");
		for(Goods goods: goodsList) {
			System.out.println(goods);
		}
		Collections.sort(goodsList);
		
	}

}


irista23 2018-12-05 09:33:02

检查一下Goods类是否实现了Comparable<Goods>,重写了compareTo()方法

  • 提问者 乃好 #1
    有重写 public class Goods implements Comparable<Goods> { @Override public int compareTo(Goods o) { //取出商品价格 double price1 = this.getPrice(); double price2 = o.getPrice(); int n = new Double(price2-price1).intValue(); return n; }
    2018-12-05 11:02:38
  • irista23 回复 提问者 乃好 #2
    如果是实现了Comparable<Goods>,并重写了compareTo()方法,代码有没有保存呢?如果也保存了,建议你把代码完整贴出来(注意不要截图),便于老师方便快速帮你解决问题
    2018-12-05 11:57:39
  • 提问者 乃好 回复 irista23 #3
    老师你好,我把代码贴在回答里面了
    2018-12-05 12:52:50
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师