gpt4 book ai didi

java - 如何统计一个单词在数组中出现的次数

转载 作者:行者123 更新时间:2023-12-02 07:47:27 30 4
gpt4 key购买 nike

我试图计算每个单词在java中的数组中出现的次数,然后显示它,但我不知道如何使用扫描仪添加到数组中,然后尝试找到一个方法这将遍历数组并显示每个单词在该数组中出现的次数。

public class Counting {

static String[] words = new String[3];
//static int[] aCounts;
private static int count;

public static void countTimesWordApperesInArray() {
int size = words.length;
for (int i = 0; i < size; i++) {
int position = i;
int count = 0;
for (int j = 0; j < size; j++) {
String element = words[i];
if (words[i].contains(element)) {
count++;
}
}
System.out.println(words[i] + " " + count);
}
}

public static void main(String[] args) {
System.out.println("Enter three Words");
Scanner scanner = new Scanner(System.in);

String input = scanner.next();

while (!("-1").equals(input)) {
words[count] = input;
count++;
input = scanner.next();
}
//print();
countDigits();
}
}

最佳答案

words[i].contains(element)更改为words[j].equals(element)

public static void countTimesWordApperesInArray() {
int size = words.length;
for (int i = 0; i < size; i += 1) {
int count = 0;

String element = words[i];
for (int j = 0; j < size; j += 1) {
if (words[j].equals(element)) {
count += 1;
}
}
System.out.println(words[i] + " " + count);
}
}

关于java - 如何统计一个单词在数组中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22464441/

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