【问题标题】:Finding a letter in a string using charAt and while loop Java使用 charAt 和 while 循环 Java 在字符串中查找字母
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 为了完整起见,您可以将字符串与字符串进行比较,使用str.substring 效率低,使用str.regionMatches 效率更高。
【解决方案2】:
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”所以它只会显示第一个的位置

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多