我有一个存储在 String
中的长文本(即 tstr1
im 代码)。现在我想将来自控制台的用户输入存储在 String[]
中(即 itemsFromArray
im 代码)。
我希望对于存储在用户输入 String[] 数组中的每个单词,系统显示该单词在长 Text String[] 数组中出现的次数。我尝试过这种方式,但问题是系统只显示数组中第一个条目的计数,但下一个条目显示为零。
btnNewButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
keyW = txtKeyword.getText();
search = textField.getText();
System.out.println("String for car = " + search);
System.out.println("String keyword = " + keyW);
WebDriver driver = new FirefoxDriver();
driver.get("https://en.wikipedia.org/wiki/" + search);
tstr1 = driver.findElement(By.xpath("//*[@id='content']")).getText();
String [] itemsFromArray = keyW.split(",");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String word : itemsFromArray){
map.put(word, 0);
}
Scanner s = new Scanner(tstr1);
while (s.hasNext()){
String word = s.next();
if (map.containsKey(word)){
map.put(word, map.get(word) + 1);
System.out.println("Word1 '" + word + "' count:" + map.get(word));
} else {
System.out.println("Word2 '" + word + "' not in map");
}
}
driver.close();
}
});
最佳答案
最好使用 Map<String, Integer>
:
// initialize a mapping that is used to map words to their count
Map<String, Integer> counter = new HashMap<String, Integer>();
// initialize all counts to 0
for (String word : itemsFromArray){
counter.put(word, 0);
}
// ...
// count words that are in map (give up those that aren't)
while (s.hasNext()){
String word = s.next();
if (counter.containsKey(word)){
counter.put(word, counter.get(word) + 1);
System.output.println("Word '" + word + "' count:" + counter.get(word));
} else {
System.output.println("Word '" + word + "' not in map");
}
}
关于java - 对于 Java 中的每个循环都有字数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32451197/