输出所有商品信息
package imooc.work2;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class GoodsManage {
Set <Goods>goodsSet=new HashSet<Goods>();
Iterator<Goods> it=goodsSet.iterator();
public void imoprtGoods() {
Goods goods1=new Goods(1000,"耳机",1000,"让声音直接进入耳朵");
Goods goods2=new Goods(4000,"手机",1001,"人工智能的产物");
Goods goods3=new Goods(7000,"电视",1002,"广播工具");
goodsSet.add(goods1);
goodsSet.add(goods2);
goodsSet.add(goods3);
}
//显示所有的商品
public void displayAllGoods() {
System.out.println("善品信息为:");
if(it.hasNext()) {
System.out.println(it.next());
}
}
}
package imooc.work2;
public class Goods {
private double price;
private String name;
private int id;
private String desp;
public Goods(double price, String name, int id, String desp) {
this.price = price;
this.name = name;
this.id = id;
this.desp = desp;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDesp() {
return desp;
}
public void setDesp(String desp) {
this.desp = desp;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((desp == null) ? 0 : desp.hashCode());
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(price);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if(this==obj) {
return true;
}
if(obj.getClass()==this.getClass()) {
Goods goods=(Goods)obj;
return goods.name.equals(name)&&goods.price==price&&goods.id==price&&goods.desp.equals(desp);
}
return false;
}
public String toString() {
return "商品名称"+name+"价格"+price+"编号"+id+"属性"+desp;
}
}
package imooc.work2;
public class Test {
public static void main(String[] args) {
GoodsManage one=new GoodsManage();
one.displayAllGoods();
}
}
为什么只输出了一个"商品信息为"
正在回答
同学你好,if是判断语句,如果it.hasNext()判断集合中有元素存在,输出一条记录就结束,而while()是循环,如果it.hasNext()存在,就会输出,直到it.hasNext()判断集合中为空,就不再输出。
如果我的回答解决了你的疑惑,请采纳。祝:学习愉快!
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星