首页 > 解决方案 > 使用 charAt 和 while 循环 Java 在字符串中查找字母

问题描述

我正在尝试制作一个程序来查看用户输入的字母是否在字符串“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.");

标签: javastringwhile-loopcharat

解决方案


您正在尝试将 achar与 a进行比较String

将 achar与 a进行比较char

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))

推荐阅读