首页 > 解决方案 > 如何根据字符串的索引打印一个字母?

问题描述

我想使用 indexOf(); 打印一个字母而不是索引位置 方法。要求是: 输入来自用户的第二个字符串。输出短语中字符串的第一个实例之后的字符。如果字符串不在短语中,则输出一个声明。例如输入为3,倒置,d。输出应该是“e”,我得到了它的一部分,它输入一个整数而不是那个特定位置的字符串。我将如何输出一个字符串?

                else if (option == 3){
                int first = 0;
                String letter = keyboard.next();
                first = phrase.indexOf(letter,1);
            if (first == -1){
                    System.out.print("'"+letter+"' is not in '"+phrase+"'");
            }
            else {
                    System.out.print(first + 1);
        }
    }

标签: java

解决方案


基于这些评论

那么,您想要的是根据用户输入的字母打印第一个字母?例如,对于单词键盘,用户输入字母“a”,第一个字母可能是“R”。是这样吗?——盖里诺·罗德拉

是的,我必须结合 indexOf(): 方法和 charAt(): 方法 – Hussain123

这个想法是根据用户输入的字母获取下一个字母。我不确定我是否理解它,但这是我的镜头

  public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);
        String phrase = "keyboard";
        String userInput = keyboard.nextLine();

        boolean notContainsInputValue = !phrase.contains(userInput);
        if (notContainsInputValue) {
            System.out.println("The input value doesn't exists");
            return;
        }

        char firstLetter = userInput.charAt(0);
        int desiredIndex = 0;
        for (int i = 0; i < phrase.length(); i++) {
            if (phrase.charAt(i) == firstLetter) {
                desiredIndex = i;
                break;
            }
        }
        System.out.println("The index for your input letter is: " + desiredIndex);
        System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
    }

输出

The index for your input letter is: 5
Next letter based on input value is: r

希望对您有所帮助。


推荐阅读