【问题标题】:method to return hashmap from text从文本返回 hashmap 的方法
【发布时间】: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


    【解决方案1】:

    这可能是因为变量 pairsCount 超出了它的范围。

    您在 if 块内部定义它,但试图在外部返回它。

    所以尝试定义 Map pairsCount = new HashMap(); 在 if (in != null) 之前

    【讨论】:

    • 这似乎对我的方法中的 return 语句有所帮助,但我在 main 中的变量 pairsCount 仍然无法解析。如果 main 正在调用该方法,不应该返回这个变量吗?
    • public static void main(String[] args) { InputStream in = System.in; in = getFileInputStream(args[0]); getHashMap(in); for( Map.Entry entry : pairsCount.entrySet() ) { System.out.printf( "%s %s -> %d\n", entry.getKey().split( "#" ) [0], entry.getKey().split("#")[1], entry.getValue()); } }
    • 首先。我认为您应该编辑原始帖子以将主要功能也包含为代码 sn-p。其次,还有一个问题是你不能说 Map pairsCount = new HashMap(); .您需要为构造函数指定类型。所以应该是 Map pairsCount = new HashMap();
    • 对于您的参考问题,在您的主函数中,您没有变量来接收函数getHashMap(in)的返回值。所以你需要使用pairCount = getHashMap(in);
    猜你喜欢
    • 2013-03-30
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多