Search code examples
javacharasciialphabet

Finding nth letter in alphabet from current letter


So I am trying to take a letter from the alphabet, input by the user, and then finding the letter that is 10 letters away, and I want it to wrap around the alphabet if the letter is 'z' or 'y' or anything that is < letter 16.

I am struggling with the looping part. I know that the alphabet is just thrown into the ASCII table with numbers that are not 1-26, so I am not sure how to deal with it. This is what I have so far.

public static void main(String[] args){

    Scanner input = new Scanner(System.in);
    System.out.println("Please input your favorite letter");
    char userLetter = input.next().charAt(0);
    char newLetter = (char) ((userLetter + 10) % 26);

    System.out.println("10 letters beyond your letter is " + newChar);

}

Can anyone help?


Solution

  • We can try mapping both lowercase and uppercase alphabet characters to a 1-26 scale, then shift and possibly wrap using the modulus. Finally, we keep track of the shift amount, so that we may add it back to generate the shifted character.

    Scanner input = new Scanner(System.in);
    System.out.println("Please input your favorite letter");
    char userLetter = input.next().charAt(0);
    
    // get the ASCII value of the input character
    int ascii = (int) userLetter;
    // compute the shift (97 for lowercase, 65 for uppercase)
    int shift = ascii > 90 ? 97 : 65;
    
    int newPosition = (ascii - shift + 10) % 26;
    newPosition += shift;
    
    char newChar = (char) newPosition;
    System.out.println("10 letters beyond your letter is " + newChar);