【发布时间】:2015-04-16 21:19:18
【问题描述】:
我正在尝试编写一个采用 InputStream 变量并将 HashMap 返回给 main 的方法。但是我被困在如何返回 HashMap 的变量上。 Java 新手,所以我不知道自己在做什么错。对于返回语句:pairCount 无法解析为变量。提前致谢。
private static Map<String, Integer> getHashMap(InputStream in)
{
if (in != null)
{
// Using a Scanner object to read one word at a time from the input stream.
@SuppressWarnings("resource")
Scanner sc = new Scanner(in);
String word;
System.out.println(" - Assignment 1 -s%n%n\n");
// Continue getting words until we reach the end of input
List<String> inputWords = new ArrayList<String>();
while (sc.hasNext())
{
word = sc.next();
if (!word.equals(null))
{
inputWords.add(word);
}
}
Map<String, Integer> pairsCount = new HashMap<>();
Iterator<String> it = inputWords.iterator();
String currentWord = null;
String previousWord = null;
Integer wordCount = 0;
while(it.hasNext())
{
currentWord = it.next();
if( previousWord != null )
{
String key = previousWord.concat( "#" ).concat( currentWord );
if( pairsCount.containsKey( key ) )
{
Integer lastCount = pairsCount.get( key );
pairsCount.put( key, lastCount + 1 );
wordCount = wordCount + lastCount;
}
else
{
pairsCount.put( key, 1 );
wordCount = 1;
}
}
previousWord = currentWord;
}
}
return (pairsCount);
}
【问题讨论】:
标签: java methods hashmap return