[英]Finding a letter in a string using charAt and while loop 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.");
您正在尝试将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))
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”,因此它将仅显示第一个的位置
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.