【发布时间】:2019-04-26 19:46:00
【问题描述】:
我正在尝试制作一个程序来查看用户输入的字母是否在字符串“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.");
【问题讨论】:
-
我不明白和“如果是,打印它在字符串中以及它在字符串中的位置”
-
是需要使用 charAt 和 while 循环,还是只需要获取字符串中的字符索引(如果该字符串存在于该字符串中)?
标签: java string while-loop charat