0

My program is supposed to count the number of occurrences a user inputted character appears in a string. For some reason, my program does not execute the for loop. Right after it prints out "Enter the string to search: ", it doesn't let me input a string and prints out: "There are 0 occurrences of '(inputted character)' in '(inputted string)'." on a new line. I need it to be able to find the occurrences of the character over any given amount of words inputted as the string. What can I do to make it function properly? Thanks.

import java.util.Scanner;

public class CountCharacters {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Enter a character for which to search: ");
        char ch = input.next().charAt(0);

        System.out.println("Enter the string to search: ");
        String str = input.nextLine();

        int counter = 0;

        for (int i = 0; i < str.length(); i++) {
            if (ch == str.charAt(i)) {
                counter++;

            }

        }
        System.out.printf("There are %d occurrences of '%s' in '%s'.", counter, ch, str);
        System.out.println();

    }

}
devnull
  • 103,635
  • 29
  • 207
  • 208
user3404250
  • 23
  • 1
  • 6

2 Answers2

4

What happens is that the next() method doesn't consume the new-line character that is entered when you press Enter. Since that character is still there waiting to be read, the nextLine() consumes it. To fix this you can add a nextLine() after the next() call:

char ch = input.next().charAt(0);
input.nextLine(); // consumes new-line character

// ...

For futher information, you could read this post.

Christian
  • 31,246
  • 6
  • 45
  • 67
2

After entering your number I guess you are pressing <enter> so this needs to be chewed up before entering your string

try

char ch = input.next().charAt(0);
input.nextLine();
System.out.println("Enter the string to search: ");
String str = input.nextLine();
Scary Wombat
  • 41,782
  • 5
  • 32
  • 62