我正在尝试编写一个接受InputStream变量的方法,并将HashMap返回给main。但是我仍然坚持如何返回HashMap的变量。 Java新手,所以我不知道我做错了什么。对于return语句: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);
}
答案 0 :(得分:0)
这可能是因为变量pairsCount超出了它的范围。
您可以在if块中定义它,但尝试将其返回到外部。
所以尝试定义Map pairsCount = new HashMap&lt;&gt;(); 在if之前(in!= null)