package com.set;
public class Goods {
private String id;// 商品编号
private String name;// 商品名称
private double price;// 商品价格
// 构造方法
public Goods(String id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
// getter和setter方法
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;
}
public String toString() {
return "商品编号:" + id + ",商品名称:" + name + ",商品价格:" + price;
}
}
二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、
二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、
二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、二、
package com.set;
import java.util.*;
public class GoodsTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner console = new Scanner(System.in);
// 定义HashMap对象
Map<String, Goods> goodsMap = new HashMap<String, Goods>();
System.out.println("请输入三条商品信息:");
int i = 0;
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++;
}
// 遍历Map,输出商品信息
System.out.println("商品的全部信息为:");
Iterator<Goods> itGoods = goodsMap.values().iterator();
while (itGoods.hasNext()) {
System.out.println(itGoods.next());
}
}
}
map2
package com.set;
import java.util.*;
import java.util.Map.Entry;
public class DictionaryDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String,String> animal=new HashMap<String,String>();
System.out.println("请输入三组单词对应的注释,并存放到HashMap中");
Scanner input=new Scanner(System.in);
//添加数据
int i=0;
while(i<3) {
System.out.println("请输入key值(单词)");
String key=input.next();
System.out.println("请输入value值(注释)");
String value=input.next();
animal.put(key, value);
i++;
}
//打印输出value的值(直接使用迭代器)
System.out.println("******************************");
System.out.println("使用迭代器输出所有的value:");
Iterator<String> it=animal.values().iterator();
while(it.hasNext()) {
System.out.print(it.next()+" ");
}
System.out.println();
System.out.println("******************************");
//打印输出key和value的值
//通过entrySet方法
System.out.println("通过entrySet方法得当key-value");
Set<Entry<String,String>>entrySet=animal.entrySet();
for(Entry<String,String>entry:entrySet) {
System.out.print(entry.getKey()+"-");
System.out.println(entry.getValue());
}
}
}