我正在尝试创建一个仅返回字母的循环。在我的代码中,我得到了我不想要的符号。如何修复我的循环,以便当我的整数为 +3 时,它只给出字母?
public static String caesarDecrypt(String encoded, int shift){
String decrypted = "";
for (int i = 0; i < encoded.length(); i++) {
char t = encoded.charAt(i);
if ((t <= 'a') && (t >= 'z')) {
t -= shift;
}
if (t > 'z') {
t += 26;
} else if ((t >= 'A') && (t <= 'Z')) {
t -= shift;
if (t > 'Z')
t += 26;
} else {
}
decrypted = decrypted + t;
}
}
最佳答案
您正在从字母中减去移位值。因此,新字母永远不可能是 > 'z'
。您应该检查它是否是 < 'a'
(或分别为 'A'
)。
StringBuilder decrypted = new StringBuilder(encoded.length());
for (int i = 0; i < encoded.length(); i++)
{
char t = encoded.charAt(i);
if ((t >= 'a') && (t <= 'z'))
{
t -= shift;
while (t < 'a')
{
t += 26;
}
}
else if ((t >= 'A') && (t <= 'Z'))
{
t -= shift;
while (t < 'A')
{
t += 26;
}
}
decrypted.append(t);
}
return decrypted.toString();
此外,您不应该使用字符串连接来生成结果。了解 StringBuilder
相反。
编辑:确保新字母在 'a' .. 'z'
范围内对于任意(正)偏移,您应该使用 while
而不是if
.
关于java - 如何循环下移字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33157954/