这段代码基本上采用一个字符串数组,一次一个地显示它,并显示每个元素出现的计数。
问题是元素编号3(“一”)在最后重复,我不知道为什么,所以我得到的输出是:
当前输出:
One 2
Two 1
Three 1
One 2
代码:
public static void main(String[] args) {
String [] myStrings = {"One", "Two", "Three", "One"};
StringCount(myStrings);
}
public static void StringCount(String [] Array)
{
int size = Array.length;
for (int i = 0; i < size; i++)
{
int count = 0;
String element = Array[i];
for (int j = 0; j < size; j++)
{
if (Array[j].equals(element)){
count ++;
}
}
System.out.println(Array[i] + " " + count);
}
}
预期输出:
One 2
Two 1
Three 1
答案 0 :(得分:2)
首先,你得到四条打印线,因为你在一个运行四次的循环中调用输出方法:
for (int i = 0; i < size; i++) // size is 4
{
...
System.out.println(Array[i] + " " + count);
}
由于您想要计算所有不同字符串的出现次数,您希望将这些字符串映射到它们的计数。问题是您事先无法知道不同字符串的确切数量。所以你必须建立这样一个地图并在其元素上再次循环(第二步):
Map<String, Integer> counts = new HashMap<>();
/* setup map */
for (int i = 0; i < size; i++) {
String element = Array[i];
/* special case for having an element the first time: */
if (!counts.containsKey(element)) {
counts.put(element, Integer.valueOf(0));
}
/* increase the count for the element and store it back in map */
int oldCount = counts.get(element).intValue();
counts.put(element, Integer.valueOf(oldCount+1));
}
/* print out values */
for(String element : counts.keySet()) {
System.out.println(element + " " + counts.get(element));
}
答案 1 :(得分:1)
使用Set
以避免重复,如下所示:
public static void StringCount(String [] Array)
{
int size = Array.length;
Set<String> existingElement = new HashSet<>();
for (int i = 0; i < size; i++)
{
int count = 0;
String element = Array[i];
for (int j = 0; j < size; j++)
{
if (Array[j].equals(element)){
count ++;
}
}
// This will print the result if and only if the element has not
// already been added into the Set
if (existingElement.add(Array[i])) {
System.out.println(Array[i] + " " + count);
}
}
}
输出:
One 2
Two 1
Three 1
答案 2 :(得分:0)
因为您检查每个元素并且您有两次,所以它将被检查两次!你需要有一组checked元素,所以当你检查元素时你把它放在set中,然后在检查下一个元素之前检查它是否在set中,如果是,则跳过它。