圆圈字母表输入字母A&编号N,打印的字母通常前面有A 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来做它应该返回字母a。
发布于 2016-04-09 06:19:39
而不是
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] + " ");
}发布于 2016-04-09 06:37:01
您可以将字符视为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);
}https://stackoverflow.com/questions/36513426
复制相似问题