我的密码怎么了?我想逆转,例如1234到4321,它没有工作!
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
for (int i =0; i < num; i++){
int n = in.nextInt();
char[] ch = ("" + n).toCharArray();
for (int j = 0; j < ch.length; j ++){
char temp = ch[j];
ch[j] = ch[ch.length - 1 -j];
ch[ch.length - 1 -j] = temp;
System.out.print(ch + " ");
}发布于 2017-11-29 11:57:04
这应该能行
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
for (int i =0; i < num; i++){
int n = in.nextInt();
string ch = n.toString();
string output = "";
for (int j = 0; j < ch.length; j ++){
output = ch[j] + output;
}
System.out.println(output);
}
}发布于 2017-11-29 12:49:19
我想这是个简单的方法,
Scanner in = new Scanner(System.in);
int num = in.nextInt();
String reverse = new StringBuilder((num + "")).reverse().toString();
System.out.println(reverse);发布于 2017-11-29 14:44:55
在您的代码中有一些问题:
try-with-resource中使用Scanner以避免源泄漏。length,您只需要它的一半。char[]打印toString()数组,因为它将返回数组对象的引用,因此必须遍历数组并按一个数组进行打印,或者使用Arrays.toString()。try (Scanner input = new Scanner(System.in)) {
int num = input.nextInt();
char[] numChars = ("" + num).toCharArray();
for (int j = 0; j < numChars.length / 2; j++) {
char temp = numChars[j];
numChars[j] = numChars[numChars.length - 1 - j];
numChars[numChars.length - 1 - j] = temp;
}
for (char c : numChars) {
System.out.print(c + " ");
}
// Or you can use this instead of the above for loop.
// System.out.print(Arrays.toString(numChars));
}https://stackoverflow.com/questions/47552211
复制相似问题