gpt4 book ai didi

java - 谁能告诉我我的java代码出了什么问题

转载 作者:行者123 更新时间:2023-12-01 07:15:29 25 4
gpt4 key购买 nike

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;


public class shift {

@SuppressWarnings("unchecked")
public static void main(String args[])
{


String speech = "Sentence:NounPhrase VerbPhrase:NounPhrase :Art Noun:VerbPhrase : Verb | Adverb Verb: Art : the | a : Verb :jumps | sings |: Noun:dog | cat | ";

HashMap<String, String> hashmap = new HashMap<String, String>();
String a;
StringTokenizer st = new StringTokenizer(speech,":");

while (st.hasMoreTokens()) {
String key=st.nextToken().trim();
String value=st.nextToken().trim();



StringTokenizer st1 = new StringTokenizer(value,"|");

while (st1.hasMoreTokens()) {

a=st1.nextToken().trim();

hashmap.put(key, a);


}


}


Set set = hashmap.entrySet();
Iterator ia = set.iterator();





while(ia.hasNext()) {
Map.Entry me = (Map.Entry)ia.next();

System.out.println(me.getKey()+"->"+me.getValue());


}
}

}

the output is
Noun->cat
NounPhrase->Art Noun
Art->a
Sentence->NounPhrase VerbPhrase
Verb->sings
VerbPhrase->Adverb Verb

此代码缺少一些要返回的值,例如未显示跳转等

最佳答案

不确定我是否完全理解了您的问题,但请记住,HashMap 只能存储每个键一个值

如果你想为键存储多个动词"Verb" ,那么您必须使用类似以下内容来声明 map :

HashMap<String, Set<String>> hashmap = new HashMap<String, Set<String>>();

并存储 "Verb" 映射到的单词一组。

这是代码的修改(工作)版本:

import java.util.*;
public class Shift {

public static void main(String args[]) {

String speech = "Sentence:NounPhrase VerbPhrase:NounPhrase :Art " +
"Noun:VerbPhrase : Verb | Adverb Verb: Art : the | " +
"a : Verb :jumps | sings |: Noun:dog | cat | ";

Map<String, Set<String>> hashmap = new HashMap<String, Set<String>>();

StringTokenizer st = new StringTokenizer(speech, ":");

while (st.hasMoreTokens()) {
String key = st.nextToken().trim();
String value = st.nextToken().trim();

StringTokenizer st1 = new StringTokenizer(value, "|");

while (st1.hasMoreTokens()) {
String a = st1.nextToken().trim();

if (!hashmap.containsKey(key))
hashmap.put(key, new HashSet<String>());

hashmap.get(key).add(a);
}
}

for (String key : hashmap.keySet())
System.out.printf("%s -> %s%n", key, hashmap.get(key));
}
}

关于java - 谁能告诉我我的java代码出了什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4054560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com