哈希图无法正常工作

Hashmap not working correctly

我已经使用散列映射构建了一个字符串构建器,但无法弄清楚为什么当我尝试打印出放入构建器中的单词时,它会求助于 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();
}


}

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

另外 replaceAll 将正则表达式作为第一个参数。 . 在正则表达式中表示 "any character",所以 txt.replaceAll(".", "") 实际上删除了任何字符。要仅删除点,请使用 txt.replaceAll("\.", ""),即在 "escape" R.E 的特殊效果上添加一个斜杠。点。或者使用 Pattern.quote,例如 txt.replaceAll(Pattern.quote("."), "")

正如@DavidConrad 所提到的,简单的事情就是只使用 replace 而不是 replaceAll,因为这从字面上接受字符串,你不需要 RE 魔法。