简体   繁体   中英

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

Compare a char to a 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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