常用类:
方法可查jdk
二:案例一 测试:
import java.util.*;
public class DictionaryDemo {
public static void main(String[] args) {
Map dictionary=new HashMap();
Scanner sc=new Scanner(System.in);
//假设三次
int i=0;
while (i<3){
i++;
System.out.println("请输入单词");
String key=sc.next();
System.out.println("请输入意思");
String value=sc.next();
dictionary.put(key,value);
}
//1.通过迭代器输出
System.out.println("迭代器输出:");
Iterator it=dictionary.values().iterator();
while (it.hasNext()){
System.out.print(it.next()+" ");
}
System.out.println("nentrySet方法输出:");
//由于Iterator 只能传一个参数,并不能得到两个值
//2.通过entrySet方法输出
Set> entrySet=dictionary.entrySet();
//使用增强型for循环
for (Map.Entry entry:entrySet){
System.out.print(entry.getKey()+"-");
System.out.print(entry.getValue());
System.out.println();
}
//查找
System.out.println("请输入要查找的单词");
boolean flag=true;
String strSearch=sc.next();
Set keyset=dictionary.keySet();
for (String key:keyset){
if(strSearch.equals(key)){
flag=false;
System.out.println("找到了"+key+"-"+dictionary.get(key));
break;
}
}
if (flag){
System.out.println(strSearch+"没有找到");
}
}
}
运行结果:
三:案例二
测试:
Good类
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;
}
//get和set方法
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;
}
}
GoodTest:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class GoodsTest {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
// 定义HashMap对象
Map goodsMap = new HashMap();
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("商品价格的格式不正确,请输入数值型数据!");
//计算机会将之前错误格式的goodsPrice值给goodsId,故再输入即可解决
console.next();
continue;
}
Goods goods = new Goods(goodsId, goodsName, goodsPrice);
// 将商品信息添加到HashMap中
goodsMap.put(goodsId, goods);
i++;
}
// 遍历Map,输出商品信息
System.out.println("商品的全部信息为:");
Iterator itGoods = goodsMap.values().iterator();
while (itGoods.hasNext()) {
System.out.println(itGoods.next());
}
}
}
运行结果:



