gpt4 book ai didi

java - HashMap 无法正常工作

转载 作者:行者123 更新时间:2023-12-01 22:00:20 25 4
gpt4 key购买 nike

我已经使用 HashMap 构建了一个字符串构建器,但无法弄清楚为什么当我尝试打印放入构建器的单词时,它会求助于 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将正则表达式作为第一个参数。 .在正则表达式中表示“任何字符”,因此 txt.replaceAll(".", "")实际上删除任何字符。要仅删除点,请使用 txt.replaceAll("\\.", "") ,即添加斜杠来“转义”R.E的特殊效果。点。或者使用Pattern.quote ,例如txt.replaceAll(Pattern.quote("."), "")

正如 @DavidConrad 提到的,简单的事情就是使用 replace而不是replaceAll ,因为这从字面上看字符串,并且您不需要 RE 魔法。

关于java - HashMap 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33640547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com