如何计算一个单词在数组中出现的次数 [英] How to count the number of times a word appears in an array
本文介绍了如何计算一个单词在数组中出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试计算每个单词在 java 中的数组中的次数然后显示它,但是我无法弄清楚我是如何使用扫描仪添加到数组中然后试图找到一个方法的它将遍历数组并显示每个单词在该数组中的次数.
I am trying to count the number of times each word is in the array in java and then display it, but I can't figure out how I am using a scanner to add to the array and then trying to find a method that will go through the array and show how many times each word is in that array.
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);
}
}
这篇关于如何计算一个单词在数组中出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文