首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >利用charArray反求整数

利用charArray反求整数
EN

Stack Overflow用户
提问于 2017-11-29 11:52:40
回答 3查看 159关注 0票数 0

我的密码怎么了?我想逆转,例如1234到4321,它没有工作!

代码语言:javascript
复制
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 + " ");
            }
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-11-29 11:57:04

这应该能行

代码语言:javascript
复制
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);
        }
}
票数 0
EN

Stack Overflow用户

发布于 2017-11-29 12:49:19

我想这是个简单的方法,

代码语言:javascript
复制
Scanner in = new Scanner(System.in);
int num = in.nextInt();
String reverse = new StringBuilder((num + "")).reverse().toString();
System.out.println(reverse);
票数 0
EN

Stack Overflow用户

发布于 2017-11-29 14:44:55

在您的代码中有一些问题:

  1. 您已经从用户那里获得了两次输入。
  2. try-with-resource中使用Scanner以避免源泄漏。
  3. 您已经遍历了整个数组的length,您只需要它的一半。
  4. 您不能用char[]打印toString()数组,因为它将返回数组对象的引用,因此必须遍历数组并按一个数组进行打印,或者使用Arrays.toString()
代码语言:javascript
复制
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));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47552211

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档