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","蘋(píng)果");
dic.put("tiger","老虎");
dic.put("lion","獅子");
Scanner scanner = new Scanner(System.in);
while (true)
{
System.out.println("請(qǐng)輸入要查詢(xún)的單詞,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("該單詞還沒(méi)有被收錄");
}
}
System.out.println("歡迎使用");
}
}
查單詞
package com.company;
import java.util.HashMap;
import java.util.Map;
/**
* Created by ttc on 2018/1/8.
*/
//一篇英文文章,單詞間用空格分割,統(tǒng)計(jì)出現(xiàn)了哪些單詞,以及每個(gè)單詞出現(xiàn)的次數(shù)。
public class wordCount {
public static void main(String[] args) {
//問(wèn)題結(jié)果
// this----------2
// is------------2
// a-------------2
// book----------1
// that----------1
// desk----------1
String article = "this this is a book that is a desk";//問(wèn)題的開(kāi)始,問(wèn)題的輸入
String[] words = article.split(" ");
//Map<String,Integer> key保存的是單詞,value保存的是該單詞出現(xiàn)的次數(shù)
Map<String,Integer> map = new HashMap<>();
//this----2
//考察單詞數(shù)組中的每一個(gè)單詞,
for(int i = 0; i < words.length; i++)
{
//考察每一個(gè)單詞,
if(map.containsKey(words[i]))//如果map的key中存在該單詞,將該單詞出現(xiàn)的次數(shù)加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>();//創(chuàng)建一個(gè)空的map
//往map中添加元素
map.put(1,"張三");
map.put(2,"lisi");
map.put(3,"wangwu");
System.out.println("排第5的是誰(shuí)");
String name = map.get(5);//查找--在map集合中查找key對(duì)應(yīng)的值
System.out.println(name);
//map.containsKey()詢(xún)問(wèn)map中是否包含某個(gè)key,返回值boolean
System.out.println(map.containsKey(3));
System.out.println(map.containsKey(33));
}