使用 charAt 和 while 循环查找字符串中的字母 Java

Finding a letter in a string using charAt and while loop Java

我正在尝试编写一个程序来查看用户输入的字母是否在字符串 "hello" 中,如果是,则打印它在字符串中以及它在字符串中的位置.错误是 "bad operand types for binary operator"

String str = "hello", guess;
int testing = 0;
Scanner scan = new Scanner(System.in);

System.out.print("Enter a letter: ");
guess = scan.nextLine(); // Enters a letter

// finds the letter in the string
while (str.charAt(testing) != guess && testing != 6) {
    testing++;       // Continues loop
}

//prints where letter is if it is in the string
if (str.charAt(testing) == guess)
    System.out.println("The letter is at "+testing);
else
    System.out.println("Could not find that letter.");

您正在尝试比较 charString

比较 charchar:

while (str.charAt(testing) != guess.charAt(0) && testing != 6)

if (str.charAt(testing) == guess.charAt(0))

我还会更改您的停止条件以避免 StringIndexOutOfBoundsException 找不到匹配项:

while (testing < str.length () && str.charAt(testing) != guess.charAt(0))

if (testing < str.length () && str.charAt(testing) == guess.charAt(0))
String str = "hello";
        char guess;
        int testing = 0;
        Scanner scan = new Scanner(System.in);

        System.out.print("Enter a letter: ");
        guess = scan.next().charAt(0); // Enters a letter

        // finds the letter in the string
        while (str.charAt(testing) != guess && testing != 5) {
            testing++;       // Continues loop
        }
        //prints where letter is if it is in the string
        if (str.charAt(testing) == guess)
            System.out.println("The letter is at "+(testing+1));
        else
            System.out.println("Could not find that letter.");

我试过了,很管用。注意这里有两个"l"所以只会显示第一个

的位置