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?

asked Aug 11, 2017 at 8:23
\$\endgroup\$

2 Answers 2

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();
answered Aug 13, 2017 at 10:02
\$\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;
 }
}
answered Aug 11, 2017 at 8:56
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.