圆形字母表

Circle Alphabet

圆形字母表 输入字母A&数字N,打印出来的字母前面往往有一个N单位(注:字母排列成一个圆圈,所以输入字母的情况是'z'且N=1,反应项目是'a') 输入 b 1 输出 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);
    }
}

如何使用字母 z 和数字 1 应该 return 字母 a

而不是

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

尝试使用取模运算符处理溢出:

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

你可以把一个字符当作一个int,直接给它加上一个偏移值。

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);
}