我正在尝试制作一个程序,查看用户输入的字母是否在字符串“ 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.");
答案 0 :(得分:4)
您正在尝试将char
与String
进行比较。
比较char
与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))
答案 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”,因此它将仅显示第一个的位置