我想计算句子中重复单词或重复单词的总数。在这里我可以打印单词但无法计算这些单词。
import java.util.*;
public class Duplicate {
public static void main(String[] args) {
String input = "Big black bug bit a big black dog on his big black nose";
//Scanner scanner = new Scanner(System.in);
//System.out.println("Enter the sentence");
//String input = scanner.nextLine();
int count;
int counter=0;
//Converts the string into lowercase
input = input.toLowerCase();
//Split the string into words using built-in function
String words[] = input.split(" ");
System.out.println("Duplicate words in a given string : ");
for(int i = 0; i < words.length; i++) {
count = 1;
for(int j = i+1; j < words.length; j++) {
if(words[i].equals(words[j])) {
count++;
//Set words[j] to 0 to avoid printing visited word
words[j] = "0";
counter=counter+1;
}
}
//Displays the duplicate word if count is greater than 1
if(count > 1 && words[i] != "0") {
System.out.println(words[i]);
}
}
System.out.println("Total Duplicate words in a given string : " +counter);
}
}
我期望输出:--
给定字符串中的重复单词:big black
给定字符串中的重复单词总数:2
输出如下:
给定字符串中的重复单词:big black
给定字符串中的重复单词总数:10
总计数显示 10,而不是 2。
守着一只汪
波斯汪
相关分类