Search code examples
javageometryalphabet

Circle Alphabet


Circle Alphabet Enter letter A & number N , printed letters are often preceded by A N units (note: the letters arranged in a circle, so the case of the input letters is 'z' and N = 1, response project is 'a') Input b 1 Output c

import java.util.Scanner;

class UnsolvedProblem {
    public static void tinh(String ch, int numb) {
        String[] str = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
                "t", "u", "v", "w", "x", "y", "z" };
        for (int i = 0; i < str.length; i++) {
            if (ch.equals(str[i]))
                System.out.print(str[i + numb] + " ");
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String ch = sc.next();
        int numb = sc.nextInt();
        tinh(ch, numb);
    }
}

How to do it with letter z and number 1 it should return letter a


Solution

  • Instead of

    if (ch.equals(str[i]))
     System.out.print(str[i + numb] + " ");
    

    Try handling overflow with the modulus operator:

    if (ch.equals(str[i])) {
     int overflowed = (i + numb) % str.length;
     System.out.print(str[overflowed] + " ");
    }