我在做一個項目,在Java中的大學,我有一個這樣的輸入:我的第一個Java項目
i 4 //that are the iteration
a nissan car motor -1 // "a" means add operation "nissan" is the element and "car e motor"
// are the tags associated to nissan
a apple fruit iphone macbook -1
a peach fruit color -1
s fr -1 // "s" is the subtag that I have to find in the tag
i 3
a soccer ball player -1
a volley ball shoes -1
s bal -1
END // "END" is the end of input
輸出:
2
2
因爲第一次迭代在它找到兩個元素的標籤以「fr」開頭, ,在第二次迭代中它找到兩個標籤以「bal」開頭的元素。
class main
{
private static boolean trovato;
public static void main (String args []) throws IOException
{
HashMap<String, HashSet<String>> map = new HashMap <String,HashSet<String>>();
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
HashSet<String> totale = new HashSet <String>() ;
String line ;
String numiter;
Integer numiter2 = 0 ;
String[] parts = null ;
HashSet<String> hs = new HashSet<String> () ;
HashSet<String> tmp = new HashSet<String> () ;
Vector <Integer> conti = new Vector<Integer>();
boolean entrato = false ;
line = stdin.readLine();
while (!line.equals("<END>"))
{
if (line.startsWith("i"))
{
map.clear();
hs.clear();
totale.clear();
}
parts = line.split("[\\s\\-1]");
if (parts[0].equals("a"))
{
hs.add(parts[1]);
for (int r = 2 ; r < parts.length ; r++)
{
map.put(parts[r], hs);
}
}
System.out.println("totale" + totale.size());
if (parts[0].equals("s"))
{
entrato = false ;
for (String key : map.keySet())
{
if (key.startsWith(parts[1]))
{
entrato = true ;
totale.addAll(map.get(key));
}
}
System.out.println(totale.size());
}
line = stdin.readLine();
}
}
}
該代碼有效,但我的老師想要一個更有效的方式來做到這一點。我不知道該怎麼做。提前感謝。
幫幫我!我應該使用SortedMap嗎?TreeMap。哪個更適合我的問題? – user3572461 2014-09-06 12:52:21