package com.company;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* Created by ttc on 2018/1/8.
*/
public class Dictionary {
public static void main(String[] args) {
Map<String,String> dic = new HashMap<String, String>();
//向字典增加词汇和释义
dic.put("dog","狗");
dic.put("cat","猫");
dic.put("apple","苹果");
dic.put("tiger","老虎");
dic.put("lion","狮子");
Scanner scanner = new Scanner(System.in);
while (true)
{
System.out.println("请输入要查询的单词,no退出");
String word = scanner.next();
if(word.equals("no"))
{
break;
}
//看字典的key中是否包含该单词
if(dic.containsKey(word))
{
System.out.println(dic.get(word));
}
else
{
System.out.println("该单词还没有被收录");
}
}
System.out.println("欢迎使用");
}
}
查单词
package com.company;
import java.util.HashMap;
import java.util.Map;
/**
* Created by ttc on 2018/1/8.
*/
//一篇英文文章,单词间用空格分割,统计出现了哪些单词,以及每个单词出现的次数。
public class wordCount {
public static void main(String[] args) {
//问题结果
// this----------2
// is------------2
// a-------------2
// book----------1
// that----------1
// desk----------1
String article = "this this is a book that is a desk";//问题的开始,问题的输入
String[] words = article.split(" ");
//Map<String,Integer> key保存的是单词,value保存的是该单词出现的次数
Map<String,Integer> map = new HashMap<>();
//this----2
//考察单词数组中的每一个单词,
for(int i = 0; i < words.length; i++)
{
//考察每一个单词,
if(map.containsKey(words[i]))//如果map的key中存在该单词,将该单词出现的次数加1
{
int count = map.get(words[i]);
count++;
map.put(words[i],count);
}
else//如果map的key中不存在该单词,将该单词添加到map中
{
map.put(words[i],1);
}
}
for(String word : map.keySet())
{
System.out.println(word+"--------"+map.get(word));
}
}
}
考试排名
public static void main(String[] args) {
//java考试排名信息
Map<Integer,String> map = new HashMap<Integer,String>();//创建一个空的map
//往map中添加元素
map.put(1,"张三");
map.put(2,"lisi");
map.put(3,"wangwu");
System.out.println("排第5的是谁");
String name = map.get(5);//查找--在map集合中查找key对应的值
System.out.println(name);
//map.containsKey()询问map中是否包含某个key,返回值boolean
System.out.println(map.containsKey(3));
System.out.println(map.containsKey(33));
}