1
\$\begingroup\$

I came up with this simple solution:

public class Main {

  /**
   * How to count occurrence of a given character in a String?
   */

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    if (!in.hasNextLine()) {
      System.out.println("You must enter a string!");
    }

    String givenString = in.nextLine();

    char givenChar = in.next().charAt(0);

    int occurance = occuranceOfChar(givenString, givenChar);

    System.out.println(givenChar + " occured " + occurance + " times!");
  }

  private static int occuranceOfChar(String givenString, char givenChar) {

    int sum = 0;

    for (int i = 0; i < givenString.length(); i++) {

      char charAtI = givenString.charAt(i);

      if (charAtI == givenChar) sum++;
    }

    return sum;
  }
}

Are there any bad practices here?

\$\endgroup\$
1
\$\begingroup\$

try-with-resources

Since Java 7, you should use try-with-resources on your Scanner for safe and efficient handling of the underlying I/O resource:

try (Scanner scanner = new Scanner(System.in)) {
    String input = scanner.nextLine();
}

Spelling

'occurance' should be spelled as 'occurrence'. :)

Stream-based processing:

Since Java 8, you can stream on the characters of a String with String.chars() (or codePoints() if you need Unicode handling) and then count the matching ones:

return givenString.chars()
        .filter(i -> i == givenChar)
        .count();
\$\endgroup\$
2
\$\begingroup\$

Your program doesn't print a prompt to the user and I couldn't make it output the warning to enter a string. I have made a few basic changes. The actual counting is done in a very basic but robust way

public class Main {

    /**
     * How to count occurrence of a given character in a String?
     */

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        System.out.println("Please enter a string to search");

        String givenString = in.nextLine();

        System.out.println("Please enter the character to search for");
        char givenChar = in.next().charAt(0);

        int occurance = occuranceOfChar(givenString, givenChar);

        System.out.println(givenChar + " occured " + occurance + " times!");
    }

    private static int occuranceOfChar(String givenString, char givenChar){

        int sum = 0;

        for (int i = 0; i < givenString.length(); i++) {

            char charAtI = givenString.charAt(i);

            if (charAtI == givenChar) sum++;
        }

        return sum;
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.