我对此非常陌生,虽然我可以使用for循环来执行此操作,但分配需要一个while循环。我尝试了下面这是行不通的。请帮忙!

package charcounter;

import java.util.Scanner;

public class CharCounter {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        char userChar = '0';
        String inputEntry = "";
        String inputCharacter = "";
        int foundOccurrences = 0;

        System.out.print("Please enter one or more words: ");
        inputEntry = in.nextLine();

        System.out.print("\nPlease enter one character: ");
        inputCharacter = in.next();
        userChar = inputCharacter.charAt(0);

        while (foundOccurrences < inputEntry.length()) {
            if (userChar == inputEntry.charAt(0)) {

            }

            System.out.println("There is " + foundOccurrences + " occurrence(s) of " + inputCharacter + " in test.");

            foundOccurrences++;
        }

    }

}

最佳答案

像这样:

        int i = 0;
        while (i < inputEntry.length()) {
            if (userChar == inputEntry.charAt(i++)) {
                foundOccurrences++;
            }
        }
        System.out.println("There is " + foundOccurrences + " occurrence(s) of " + inputCharacter + " in test.");


修复了错误

10-07 22:56