简体   繁体   English

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

[英]Finding a letter in a string using charAt and while loop Java

I'm trying to make a program that sees if a user-entered letter is in the string "hello", and if it is, print that it is in the string and where it is in the string. 我正在尝试制作一个程序,以查看用户输入的字母是否在字符串“ hello”中,如果是,则打印该字符串在字符串中以及字符串在字符串中的位置。 The error is "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.");

You are trying to compare a char to a String . 您正在尝试将charString进行比较。

Compare a char to a char : 比较一个char和一个char

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

and

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

I'd also change your stopping condition to avoid StringIndexOutOfBoundsException when no match is found: 如果找不到匹配项,我还将更改您的停止条件以避免StringIndexOutOfBoundsException

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

and

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.");

I've tried this and it works. 我已经尝试过了,并且有效。 Note that there are two "l" so it will show only the position of the first one 请注意,有两个“ l”,因此它将仅显示第一个的位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM