Hashmap无法正常工作

时间:2015-11-10 22:05:55

标签: java hashmap stringbuilder

我使用哈希映射构建了一个字符串构建器,但无法弄清楚为什么当我尝试打印出构建器中的单词时,它会在countWords方法中使用else。我做错了什么导致它打印出{=1}而不是用户输入的实际单词?

import java.util.HashMap;
import java.util.Scanner;

public class HashStringBuilder {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    String txt = readText();
    String[] words = txtToWords( normalize(txt) );

    HashMap<String, Integer> wordCount = countWords( words );

    for (int i = 0; i < words.length; i++){
        System.out.println(wordCount);
    }
}

public static HashMap<String, Integer> countWords( String[] words ) {
    HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
    for( String word : words ) {
        if( wordCount.containsKey(word) ) {
            int count = wordCount.get(word);
            count = count + 1;
            wordCount.put(word, count );
        } else {
            wordCount.put(word, 1 );
        }
    }

    return wordCount;
}


public static String[] txtToWords( String txt ) {
    return txt.split(" ");
}

public static String normalize( String txt ) {
    txt = txt.toLowerCase();
    // You all can come up with a better way
    txt=txt.replaceAll("!", "");
    txt=txt.replaceAll(".", "");
    txt=txt.replaceAll("&", "");
    txt=txt.replaceAll("'", "");

    return txt;
}

public static String readText() {
    System.out.println( "Please enter the text to be processed.");
    String stop = "** STOP **";
    System.out.println( "Enter: \"" + stop + "\" to stop");

    StringBuilder results = new StringBuilder();
    Scanner input = new Scanner( System.in );
    while( true ) {
        String line = input.nextLine();
        if( line.contains(stop)) {
            break;
        } else {
            results.append( line + " ");
        }

    }

    return results.toString().trim();
}


}

1 个答案:

答案 0 :(得分:3)

您需要打印wordCount.get(words[i])

同样replaceAll将正则表达式作为第一个参数。 .表示&#34;任何角色&#34;在正则表达式中,txt.replaceAll(".", "")实际上删除了任何字符。要仅删除点,请使用txt.replaceAll("\\.", ""),即添加斜线到&#34; escape&#34; R.E.的特殊效果点。或者使用Pattern.quote,例如txt.replaceAll(Pattern.quote("."), "")

正如@DavidConrad所提到的,简单的事情就是使用replace代替replaceAll,因为这会逐字逐句,而你不需要RE魔法。