Bidimap大小始终为1

时间:2014-09-16 05:33:37

标签: java string

我正在向Bidimap输入值。在每个循环中,我将值放入Bidimap,我也打印出Bidimap的大小。它总是1.我还通过debbugger检查了map的值,它只显示了一个值,它是在地图中最近一次迭代中放入的当前值。这里出了什么问题?我怎么想在Bidimap中保存键值。

请在下面找到完整的代码。

public static void main(String args[])
    {
        //Read file
        BufferedReader br = null;

        int wordCount=0;
        String wordArray[] = null;
        BidiMap<String, Integer> map = new DualHashBidiMap<String, Integer>();


        try {   
            String sCurrentLine;

            br = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\IASTATE\\test.txt"), StandardCharsets.UTF_16));

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
                wordArray = sCurrentLine.split("\\s+");
                wordCount += wordArray.length;
            }

            //Read word 1,word 2,word 3
            int count;
            String key;
            for(int i=0;i<wordArray.length;i++)
            {
                    key=wordArray[i]+wordArray[i+1]+wordArray[i+2];

                //Compare Hashmap if the String {'word 1','word 2','word 3'}
                //exists
                if(map.containsKey(key))
                {
                    //If exists increment counter
                    count=(Integer) map.get(key);
                    count++;
                    map.put(key, count);
                }
                else
                {
                    //If doesnot exist push String {'word 1','word 2','word 3'} 
                    //in the Hashmap and initialize counter to 1
                    map.put(key, 1);
                }
                key=null;
                System.out.println("Size of Map"+map.size());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

test.txt内容

This is line one
This is line two
This is line three
This is line four

1 个答案:

答案 0 :(得分:0)

您正在阅读该文件的每一行,但在 之后,您还没有处理任何这些行:

while ((sCurrentLine = br.readLine()) != null) {
    System.out.println(sCurrentLine);
    wordArray = sCurrentLine.split("\\s+");
    wordCount += wordArray.length;
}

// Now you're messing about with wordArray, which is the _last_ line.

可能您的意图是将每行的所有单词>追加到wordArray数组但不是<\ n>你正在做什么。

这意味着您只需处理文件的 last 行。如果最后一行是真正的&#34;这是第四行&#34;,我仍然期待两个条目,一个用于&#34;这是行&#34;另一个用于&#34;是第四行&#34;。但是在你开始担心之前我会解决上面提到的问题。

通过修复它,我的意思是每次读入一行时都不会覆盖wordArray,而是附加到该数组。