开发者社区> 问答> 正文

为什么此代码显示输出:0?我输入15时应该得到输出51

输出应为51作为输入15,为什么其输出显示为0。以下部分包括将代码重新排列为降序并将数组转换为int并最后返回g。

public class ExerciseA2 {
    public static int sortDesc(final int num) {
        //Your code
        int h = Integer.toString(num).length();
        int[] arr = new int[h];
        int u,l,g = 0;
        for(int i = 0;i < arr.length;i++){
            for(int q = 1;q < arr.length-1;q++){
                if(arr[i] < arr[q]){
                    u = arr[i];
                    arr[i] = arr[q];
                    arr[q] = u;

                }
            }
        }

      for(int z = 0; z < arr.length;z++)
            g = (g*10)+arr[z];

       return g;
    }

    public static void main(String[] args) {
        System.out.print(sortDesc(15));
    }
}

展开
收起
垚tutu 2019-12-04 16:25:47 979 0
1 条回答
写回答
取消 提交回答
  • #include

    您的代码中有一些问题。

    您没有初始化arr数组。默认情况下,在Java中int数组中的值为0,这就是为什么要获得0的原因。 您可以通过以下方式对其进行初始化:

    String n = Integer.toString(num);
    
    for (int i = 0; i < n.length(); i++) {
        // there are many ways to convert a char to a string, 
        // I will leave that for you to explore which is the efficient/suitable. 
        // For now, this works.
        // Remember to convert to int, or you will get ASCII values, which will be integers, just not the ones you want.
        arr[i] = Integer.parseInt(n.charAt(i) + "");
    }
    
    

    现在有了数组,嵌套循环中又有一个问题。当大小为2时,条件返回false,它将永远不会执行。 您可以通过以下方式解决此问题:

    for (int q = i + 1; q < arr.length; q++) {
        // your code here
    }
    
    

    希望这可以帮助。祝好运。

    2019-12-04 16:26:32
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载