How do I print a letter based on the index of the string?

后端 未结 2 1063
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-26 01:07

I want to print a letter instead of the index position using the indexOf(); method. The requirement is that: Inputs a second string from the user. Outputs the character after t

相关标签:
2条回答
  • 2021-01-26 01:25

    String.charAt(index)

    You can access a single character, or a letter, by caling método charAt() from String class

    Example

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        String phrase = keyboard.nextLine();
        char firstLetter = phrase.charAt(0);
        System.out.println("First Letter : " + firstLetter);
    }
    

    So, running this code, assuming the input is StackOverFlow, the output will be S

    In your code I think doing the follow will work:

    Your Code

     String letter = keyboard.next();
     first = letter.charAt(0);
    

    That might help!

    0 讨论(0)
  • 2021-01-26 01:28

    Based on those comments

    So, what you want is print the first letter based on a letter the user has input? For example, for the word Keyboard, and user inputs letter 'a' the first letter might be 'R'. Is that it? – Guerino Rodella

    Yes, I have to combine both the indexOf(): method and the charAt(): method – Hussain123

    The idea is get next letter based on user input letter. I'm not sure I wunderstood it, but this is my shot

      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 Output

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

    Hope that helps you.

    0 讨论(0)
提交回复
热议问题