Count the occurrences of a letter in a string

前端 未结 10 1539
礼貌的吻别
礼貌的吻别 2021-01-21 03:42

I am trying to write a for loop in Java that will count the occurrences of a letter in a string. The user will enter the letter to count and the string in which to search. This

10条回答
  •  感情败类
    2021-01-21 03:58

    your Scanner class has not moved to the next line after reading the character

    letter = in.next().charAt(0);
    

    add another in.nextLine() before reading the input string

        System.out.println("Enter a character for which to search");
        letter = in.next().charAt(0);
        in.nextLine();
        System.out.println("Enter the string to search");
        sentence = in.nextLine();
    

    old thread but hope this helps :)

提交回复
热议问题