简体   繁体   中英

method to return hashmap from text

I am trying to write a method that takes an InputStream variable and returns a HashMap back to main. However I'm stuck on how to return the variable of HashMap. New to Java so I do not know what I'm doing wrong.For the return statement: pairsCount cannot be resolved to variable. Thanks in advance.

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);

}

This is probably because variable pairsCount is out of its scope.

You define it inside of the if block but trying to return it outside.

So try define Map pairsCount = new HashMap<>(); before the if (in != null)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM