Nguyen Cong Tri
Nguyen Cong Tri

Reputation: 11

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

Upvotes: 0

Views: 3161

Answers (2)

Sam
Sam

Reputation: 10016

You can treat a character as an int and add an offset value to it directly.

static char tinh(char c, int rotation) {
    int offset = (int)c - (int)'a'; // find the position of this character in the alphabet
    int newoffset = (offset + rotation) % 26; // calculate the new position
    return (char)((int)'a' + newoffset);
}

Upvotes: 0

nhouser9
nhouser9

Reputation: 6780

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] + " ");
}

Upvotes: 1

Related Questions