名字重复为什么系统识别不了呢
来源:4-9 商品信息添加优化
weixin_慕容0194784
2019-04-09 16:04:36
代码就是这样的,怎么修改呢
Scanner sc=new Scanner(System.in);
Map<String,Goods> Goods1=new HashMap<String,Goods>();
System.out.println("请输入三个商品的信息");
int i=0;
while(i<3) {
System.out.println("请输入第"+(i+1)+"个的商品名");
String Goodsname=sc.next();
if(Goods1.containsKey(Goodsname)) {
System.out.println("商品名重复请重新输入");
continue;
}
System.out.println("请输入第"+(i+1)+"个的编号");
String Goodsnumber=sc.next();
if(Goods1.containsKey(Goodsnumber)) {
System.out.println("编号重复请重新输入");
continue;
}
System.out.println("请输入第"+(i+1)+"个的价格");
double Goodsprice=0;
try {
Goodsprice=sc.nextDouble();
}catch(java.util.InputMismatchException e) {
System.out.println("输入有误,请输入数字");
sc.next();
/*
* next()方法就是从从控制台接收输入的数据。
* 程序里nextDouble()出错就进入异常catch里了,而catch中执行了continue,继续下次循环。执行了next()方法。
* 由于nextDouble()输入的错误信息,系统不会给你自动删除掉,所以这里就会保存在next()方法中了。
*/
continue;
}
Goods one=new Goods(Goodsname,Goodsnumber,Goodsprice);
Goods1.put(Goodsnumber, one);
i++;
}
//输出商品的全部信息
System.out.println("输入商品信息为:");
Iterator<Goods> it=Goods1.values().iterator();
while(it.hasNext()) {
System.out.println(it.next()+" ");1回答
代码上不能用containsKey()来商品名称是否包含,因为你下面添加到集合中的key是商品编号,逻辑上应该先检查商品编号key,再检查商品名称等,你可以参照课程如下源码对照一下修改

while (i < 3) {
System.out.println("请输入第" + (i + 1) + "条商品信息:");
System.out.println("请输入商品编号:");
String goodsId = console.next();
// 判断商品编号id是否存在
if (goodsMap.containsKey(goodsId)) {
System.out.println("该商品编号已经存在!请重新输入!");
continue;
}
System.out.println("请输入商品名称:");
String goodsName = console.next();
System.out.println("请输入商品价格:");
double goodsPrice = 0;
try {
goodsPrice = console.nextDouble();
} catch (java.util.InputMismatchException e) {
System.out.println("商品价格的格式不正确,请输入数值型数据!");
console.next();
continue;
}
Goods goods = new Goods(goodsId, goodsName, goodsPrice);
// 将商品信息添加到HashMap中
goodsMap.put(goodsId, goods);
i++;
}相似问题
回答 1
回答 1