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

Coo*_*per 0 java string while-loop charat

我正在尝试制作一个程序,查看用户输入的字母是否在字符串“ hello”中,如果是,请打印该字符串在字符串中以及字符串在字符串中的位置。错误是“二进制运算符的错误操作数类型”

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.");
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 5

您正在尝试将A char与A 进行比较String

将a char与a 进行比较char

while (str.charAt(testing) != guess.charAt(0) && testing != 6)
Run Code Online (Sandbox Code Playgroud)

if (str.charAt(testing) == guess.charAt(0))
Run Code Online (Sandbox Code Playgroud)

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

while (testing < str.length () && str.charAt(testing) != guess.charAt(0))
Run Code Online (Sandbox Code Playgroud)

if (testing < str.length () && str.charAt(testing) == guess.charAt(0))
Run Code Online (Sandbox Code Playgroud)