Click here to Skip to main content
15,886,422 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Java
import java.util.*;
import java.lang.*;
public class MyClass {
  public static void main(String args[]) {
    Scanner in = new Scanner(System.in);
    int count = 0;
    String inputEntry = in .nextLine();
    String inputCharacter = in .nextLine();
    if (inputCharacter.length() != 1) {
      System.out.println("Please enter single character");
System.exit(0);

    } else {
      for (int i = 0; i < inputEntry.length(); i++) {
        if (inputEntry.charAt(i) == inputCharacter) {
          count++;
        }
      }
      System.out.println("There is " + count + " occurence(s) of '" + inputCharacter + "' in " + inputEntry);
    }
  }
}


What I have tried:

debug the error please. it shows an error in the line if (inputEntry.charAt(i) == inputCharacter) i dont understand how to debug this.
Posted
Updated 1-Jul-18 13:23pm
Comments
[no name] 1-Jul-18 13:28pm    
inputCharacter is of type string
While inputEntry.charAt(i) returns a char

if (inputEntry.charAt(i) == inputCharacter.charAt(0)) will solve the problem.
Afzaal Ahmad Zeeshan 1-Jul-18 14:31pm    
Virtual 5. :-)
Peter_in_2780 1-Jul-18 18:52pm    
Post it as the solution.

1 solution

The fast version would be as follows:

if (inputEntry.charAt(i) == inputCharacter.charAt(0)) {
	          count++;
	        }


What happens is that you have declared inputCharacter as a String object, so obviously is not really a char or char[].
A better version for your little code snippet would be (since your little char will always be of single unit size):

int countz = StringUtils.countMatches(inputEntry, inputCharacter);


This allows for actual substring comparisons also. If you are really, really sure you want just one character inside your string, to be accounted for, then just use something like this:

int countz = StringUtils.countMatches(inputEntry, inputCharacter.charAt(0));
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900