Patrick C
Patrick C

Reputation: 3

How to count instances of an specified char in a string in Java?

I've looked through everything relevant I can find on here, but for some reason nothing is helping. Whenever I run this I always end up with a result of 0. And no, I can not use other libraries for this (I saw some awesome solutions that have it down to one line, but I can't do that)

public void process()
{
    Scanner input = new Scanner(System.in);
    System.out.println("Enter your String:");
    String in_string = input.nextLine();

    Scanner input2 = new Scanner(System.in);
    System.out.println("Press 1 to count the occurrence of a particular letter.");
    System.out.println("Press 2 to count the total words in your input sentance.");
    System.out.println("Press 3 to change your input sentance.");
    System.out.println("Press 4 to exit.");

    int option = input2.nextInt();

    if (option==1)
    {
        System.out.println("Choose your letter: ");
        String in_occurence = input.nextLine();


        for(int i = 0 ; i < in_string.length(); i++)
        {
            if(in_occurence.equals(in_string.charAt(i)))
            {
                charCount++;
            }
        }
        System.out.println(charCount);
    }

Upvotes: 0

Views: 205

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213351

You are comparing a String with a char using String#equals(). That will always give you false.

For example:

System.out.println("a".equals('a'));  // false

You should convert the String to char by getting character at index 0 before comparison:

if(in_occurence.charAt(0) == in_string.charAt(i))

or, just declare in_occurrence as char type:

char in_occurence = input.nextLine().charAt(0);

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533740

You are comparing a String to a char which is never equal even if the String contains that char.

What you want is

if (in_occurance.charAt(0) == in_string.charAt(i)) // compare char

Upvotes: 1

Related Questions