方法返回int,而不是字符的java中
问题描述:
就像标题我有在Java中的方法,我写了一个问题说明。这是代码:方法返回int,而不是字符的java中
public static char shift(char c, int k) {
int x = c;
int d = c - 65 + k;
int e = c - 97 + k;
if (x > 64 && x < 91 && d >= 0) {
c = (char) (d % 26 + 65);
} else if (x > 96 && x < 123 && e >= 0) {
c = (char) (e % 26 + 97);
}
if (x > 64 && x < 91 && d < 0) {
c = (char) ((d + 26) % 26 + 65);
} else if (x > 96 && x < 123 && e < 0) {
c = (char) ((e + 26) % 26 + 97);
}
return c;
}
我想转移字母表中的字母。代码工作完美,如果我这样使用它(凯撒Chiper):
String s = " ";
String text = readString();
int k = read();
for (int i = 0; i < text.length(); i++) {
char a = text.charAt(i);
int c = a;
int d = a - 65 + k;
int e = a - 97 + k;
if (c > 64 && c < 91 && d >= 0) {
a = (char) (d % 26 + 65);
} else if (c > 96 && c < 123 && e >= 0) {
a = (char) (e % 26 + 97);
}
if (c > 64 && c < 91 && d < 0) {
a = (char) ((d + 26) % 26 + 65);
} else if (c > 96 && c < 123 && e < 0) {
a = (char) ((e + 26) % 26 + 97);
}
s += a;
}
System.out.println(s);
}
我不明白为什么该方法转变返回时,我使用这样的整数:转变(“C”,5);它返回104,这是h的十进制数。我是一个java初学者和一个慢人。
预先感谢您。
答
你的错误是,你可能会增加两个字符的统一码。 如果你做这样的事会发生这种情况:
System.out.println('b' + 'a');
或在您的情况
System.out.println(shift('c', 5) + 'a');
要获得期望的结果,焦炭打印前转换为字符串:
String result = Character.toString(shift('c', 5));
System.out.println(result + 'a');
或
System.out.println(shift('c', 5) + "a");
char是一个int tooo –
你是如何使用shift()的返回值的? –
我知道,但我想该方法返回一个字符。如果我写:char a = shift('c',5); 的System.out.println(一);它显示我104而不是'h'。 – Ralu