Java 方法从文本返回hashmap
我正在尝试编写一个方法,该方法接受一个InputStream变量并将一个HashMap返回到main。但是,我一直在研究如何返回HashMap的变量。Java新手,所以我不知道自己做错了什么。提前谢谢Java 方法从文本返回hashmap,java,methods,hashmap,return,Java,Methods,Hashmap,Return,我正在尝试编写一个方法,该方法接受一个InputStream变量并将一个HashMap返回到main。但是,我一直在研究如何返回HashMap的变量。Java新手,所以我不知道自己做错了什么。提前谢谢 private static Map<String, Integer> getHashMap(InputStream in) { if (in != null) { // Using a Scanner object to read one wor
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);
}
private静态映射getHashMap(InputStream-in)
{
if(in!=null)
{
//使用扫描仪对象从输入流中一次读取一个单词。
@抑制警告(“资源”)
扫描仪sc=新扫描仪(英寸);
字符串字;
System.out.println(“-Assignment 1-s%n%n\n”);
//继续获取单词,直到输入结束
List inputWords=new ArrayList();
while(sc.hasNext())
{
word=sc.next();
如果(!word.equals(null))
{
输入单词。添加(单词);
}
}
Map pairsCount=新HashMap();
Iterator it=inputWords.Iterator();
字符串currentWord=null;
字符串previousWord=null;
整数字数=0;
while(it.hasNext())
{
currentWord=it.next();
if(上一个单词!=null)
{
String key=previousWord.concat(“#”).concat(currentWord);
if(成对计数容器(键))
{
整数lastCount=pairsCount.get(键);
pairsCount.put(键,lastCount+1);
wordCount=wordCount+lastCount;
}
其他的
{
成对计数。放置(键,1);
字数=1;
}
}
前一个字=当前字;
}
}
返回(对计数);
}
这可能是因为变量pairsCount超出了其范围
您在if块内部定义它,但尝试在外部返回它
因此,请尝试定义Map pairscont=newhashmap();
在if(in!=null)之前,它似乎有助于我的方法中的return语句,但main中的变量pairscoount仍然无法解析。如果main正在调用该方法,该变量不应该返回吗?public static void main(String[]args){InputStream in=System.in;in=getFileInputStream(args[0]);getHashMap(in);for(Map.Entry:pairscout.entrySet()){System.out.printf(“%s%s->%d\n”,Entry.getKey().split(“#”)[0],entry.getKey().split(“#”)[1],entry.getValue());}首先。我认为您应该编辑您的原始帖子,将主函数也作为代码段包含在内。其次,还有一个问题是不能说Map pairscont=newhashmap()。您需要指定构造函数的类型。所以应该是Map pairsCount=new HashMap();对于引用问题,在main函数中,没有变量来接收函数getHashMap(in)的返回值。因此,您需要使用pairscont=getHashMap(in);