java - 遍历哈希图时数组索引越界异常
问题描述
我正在尝试编写一个 java 程序来找出字符串中出现两次的单词数,但我遇到了一个异常:
数组索引越界
输入:
2 10 恨爱和平 爱和平 恨爱和平 爱和平 8 汤姆杰瑞 托马斯 汤姆杰瑞的勇气 汤姆的勇气
输出:
1 2
完整的代码是:
class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0){
int n = sc.nextInt();
int count = 0;
String str = sc.next();
String strArray[] = str.split(" ");
HashMap <String,Integer> wordCount = new HashMap<String,Integer>();
for(int i=0;i<n;i++){
if(wordCount.containsKey(strArray[i])){
wordCount.put(strArray[i],wordCount.get(strArray[i])+1));
}
else{
wordCount.put(strArray[i],1);
}
}
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
if(entry.getValue()==2)
count++;
}
System.out.println(count);
t--;
}
}
}
解决方案
String str = sc.next();
此代码仅获取一个单词,但您打算获取n
单词。
您可以摆脱数组,因为它是不必要的,然后使用:
for(int i=0;i<n;i++){
String word = sc.next();
if(wordCount.containsKey(word)){
wordCount.put(word,wordCount.get(word)+1));
}
else{
wordCount.put(word,1);
}
}
但是,更简洁的书写方式是:
for(int i=0;i<n;i++){
wordCount.compute(sc.next(), (word,count)-> (count==null)? 1 : count+1);
}
推荐阅读
- asp.net-mvc - UserManager.UpdateSecurityStamp reverts user data
- java - 我如何遍历对象的 LinkedHashSet?
- php - if else 怎么写
- jenkins - 如何重启在windows机器上运行的jenkins
- c++ - C++ 获得“第二个命令行参数”
- sql - 我想按列显示列值组的总和。如何显示?
- visual-studio-code - Search selected text in all workspace files without having to hit the enter key to actually start the search?
- javafx - JavaFXML 创建新场景
- git - Yocto throws a git Fatal Error "Please tell me who you are" after after successful Bitbake build
- android - 当外部库中抛出异常时,Android Studio 挂起