【发布时间】:2018-04-14 21:55:50
【问题描述】:
我如何从 hashmap 交换值和键,用户从键盘给出 stringbuilder 并用 java 中的新值替换 stringbuilder 中的一个单词?我想制作一个反向翻译俚语互联网词典。例如,如果我给了这个字符串“笑和大声“在tsanlation之后我想要字符串“loI”。我创建了一个hasmap,它是我的字典并包含这些值{fyi”,“供您参考”);(“dae”,“其他人”);( "thx","thank you"); ("omg","Oh my god"); ("lol","laughing out lound");. 另外如果用户输入字符串“laugh out and lound” oytput“大声笑”。
我的代码是: 包javaapplication6;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
公共类 JavaApplication6 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String threeWords;
//create stringbuilder
StringBuilder acronym = new StringBuilder();
Scanner scan = new Scanner(System.in);
//o xrhsths dinei eisodo thn protash poy thelei na metafrasei
System.out.println("Eisigage thn protasi sou pou theleis na metafraseis:\n ");
threeWords = scan.nextLine();
threeWords = threeWords.toLowerCase(); //Changing it to lower case
acronym.append(threeWords);
System.out.println(" To string pou eisigages einai: " + acronym +"\n");
//dhmiougroum ena pinaka pou periexei mia mia thn lejei jexorista apo thn protash pou
//edose o xrhsths oste na mporoume na broume pio eukola thn leji pou einai gia metafrash sto
//lejiko
String[] threeWordsArray = threeWords.split(" ");
//dhmiougria lejikou me thn slang tou internet me thn xrisi hashmap
HashMap<String,String> dictionary = new HashMap <String,String>(10);
//Prosthiki lejeon sto lejiko mas
dictionary.put("fyi", "for your information");
dictionary.put("dae", "Does anyone else");
dictionary.put("thx","thank you");
dictionary.put("omg","Oh my god");
dictionary.put("lol","laughing out lound");
HashMap<String, String> reversedHashMap = new HashMap<String, String>();
for (String key : dictionary.keySet()){
reversedHashMap.put(dictionary.get(key), key);
}
System.out.println("reversedHasmap"+reversedHashMap);
for(String word : threeWordsArray) {
if (reversedHashMap.containsKey(word)) {
String definition = reversedHashMap.get(word);
System.out.println("h metafrash einai: \n" + definition);
int index=acronym.indexOf(word);
System.out.println("index:"+index);
acronym.insert(index,definition);
}
else {
System.err.println("Word not found");
}//end if
}//end for
System.out.println("To string metafrasmeno einai: " + acronym);
}
}
但我对 for 有疑问 for(String word : threeWordsArray) {
if (reversedHashMap.containsKey(word)) {
String definition = reversedHashMap.get(word);
System.out.println("h metafrash einai: \n" + definition);
int index=acronym.indexOf(word);
System.out.println("index:"+index);
acronym.insert(index,definition);
}
else {
System.err.println("Word not found");
}//end if
}//end for
找不到与 reversedHashMap 键匹配的输入。
【问题讨论】:
-
你到底想要什么,我不明白?到目前为止你做了什么?
-
什么?显示一些输入 + 输出以及到目前为止您尝试过的内容。
-
将值放在和之前,然后将其返回键,但直到 StringBuilder 成为键盘之后。最简单!
-
什么是逆向字典?展示您的代码以及您想要实现的目标以及您尝试过的内容,而不是尝试解释它。
标签: java dictionary hashmap stringbuilder