javaarraysinputcountpoker

Code to count how many occurrences of an element are found in a string java


I have this code here and it makes sense to me that it would print out how many instances occur in the array of the element at array[i]. The count never goes above one, what am I doing wrong?

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.");
                }
            }
        }
    }
}

Solution

  • Your comparison of the datatype String won't work unless it's the same instance. To just check if the strings are having the same characters you should use .equals(). Keep in mind that the comparison of Integer (not int) also works like this. The reason behind that is that String is a class and not a primitve type. Also read up on this post.

    So with

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

    you should be fine.


    Additional (more readable) solution

    To give you an advanced approach on how to count same values i created a small sample for you. The function you need is groupingBy. You group all values of a list in one single attribute while counting the occurences.

    Example

    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.");
    }