0

我在这里有这段代码,它会打印出在数组 [i] 的元素的数组中出现了多少个实例,这对我来说很有意义。计数永远不会超过一,我做错了什么?

import java.util.Scanner;
public class poker
{
    public static void main(String [] args)
    {
        Scanner scan = new Scanner(System.in);
        String[] array = new String[5];
        for(int i = 0; i < array.length; i++)
        {
            array[i] = scan.nextLine();
        }
        for (int i = 0; i < array.length; i++) {
            int count = 0;
            for (int j = 0; j < array.length; j++) {
                {
                    if (array[i] == array[j]) {
                        count++;
                    }

                }
                if (count >= 3) {
                    System.out.println(array[i] + " exists " + count + " times.");
                }
            }
        }
    }
}
4

4 回答 4

2

除非它是同一个实例,否则您对数据类型的比较String将不起作用。要检查字符串是否具有相同的字符,您应该使用.equals(). 请记住,Integer(not int) 的比较也是这样工作的。其背后的原因是这String是一个类而不是原始类型。还阅读了这篇文章

所以随着

if (array[i].equals(array[j])) {
    count++;
}

你应该没事。


附加(更易读)的解决方案

为了给你一个关于如何计算相同值的高级方法,我为你创建了一个小样本。您需要的功能是groupingBy. 在计算出现次数时,您将列表的所有值分组到一个属性中。

例子

Map<String, Long> nameAndCount = Arrays.asList(array).stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

for(Entry<String, Long> entry : nameAndCount.entrySet()) {
    System.out.println(entry.getKey() +  " exists " + entry.getValue()+ " times.");
}
于 2020-03-26T13:34:56.840 回答
1

这个

if (array[i] == array[j])

仅当引用相同时才为真,如果要比较字符串值,请使用

if (array[i].equals(array[j]))
于 2020-03-26T13:20:41.103 回答
1

要检查java中字符串的相等性,您必须使用equals()function。
将线路更改为if (array[i].equals(array[j])),您就可以开始了!
仅当两个数组元素的引用地址相同时,运算符==才会返回 true,这就是您永远不会得到超过 1 的计数的原因,因为每个引用地址都是唯一的。

于 2020-03-26T13:26:10.740 回答
0
package com.report.automation;

import java.util.HashMap;
import java.util.Map;

public class Frequency {
    public static void main(String[] args) {
        String value[] = { "Mukesh", "Mukesh", "Sasi", "Senthil", "Mukesh", "Mukesh" };
        String match = "Mukesh";
        int count = 0;
        for (int j = 0; j <= 5; j++) {
            if (match.equals(value[j])) {
                count++;
            }
        }
        System.out.println(count);
    }
}
于 2021-04-08T11:26:41.257 回答