使用charAt和while循环Java

时间:2018-11-24 15:12:38

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

2 个答案:

答案 0 :(得分:4)

您正在尝试将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))

答案 1 :(得分: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”,因此它将仅显示第一个的位置