You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java递归程序问题:查找升序序列中最后一个0的位置

Java递归程序问题分析与修复

问题根源

  1. 未执行排序操作:你的需求是先将数组升序排列后,再查找最后一个0的位置,但当前代码仅通过checkNum检查数组是否有序,完全没有对输入的无序数组做排序。比如输入1,2,0时,原数组还是[1,2,0],直接遍历自然找不到正确的0位置。
  2. checkZero逻辑错误:
    • 当前代码是统计0的个数,而非查找最后一个0的位置;
    • 缺失递归终止条件,当i超过数组长度时会触发数组越界异常;
    • 函数内重复调用checkNum(0)属于冗余操作,毫无意义。
  3. checkNum函数定位错误:这个函数只能检查数组是否有序,但你需要的是主动将数组排序,而非仅做有序性检查。

修复步骤

  • 添加递归排序函数(比如递归版冒泡排序),先将输入数组处理为升序;
  • 重写查找最后一个0的递归逻辑:通过从后往前递归查找第一个0的位置(升序数组中,最后一个0就是从后数第一个0),或者从前往后遍历记录最后一个0的索引,再转换为1开始的计数;
  • 删除冗余的checkNum调用,将排序逻辑整合到主流程中。

修复后的完整代码

import java.util.Scanner;

public class Main {
    
    static Scanner sc; 
    public static int[] a;
    
    // 递归输入数组
    public static void inputArr(int i) {
        if (i < a.length) {
            a[i] = sc.nextInt();
            inputArr(i + 1);
        }
    }

    // 递归冒泡排序(升序)
    public static void bubbleSort(int n) {
        if (n == 1) {
            return;
        }
        for (int i = 0; i < n - 1; i++) {
            if (a[i] > a[i + 1]) {
                int temp = a[i];
                a[i] = a[i + 1];
                a[i + 1] = temp;
            }
        }
        bubbleSort(n - 1);
    }

    // 递归查找最后一个0的位置(从1开始计数)
    public static int findLastZero(int i) {
        if (i >= a.length) {
            return 0; // 遍历完没找到0,返回0
        }
        int pos = findLastZero(i + 1);
        if (pos != 0) {
            return pos; // 后面已经找到0,直接返回该位置
        }
        return a[i] == 0 ? (i + 1) : 0; // 当前是0且后面没0,返回当前位置(+1转1开始计数)
    }
    
    public static void main(String[] args) {
        sc = new Scanner(System.in);
        
        int count;
        System.out.print("count:");
        count = sc.nextInt();
        a = new int[count];
        
        System.out.println("numbers:");
        inputArr(0); 

        // 先对数组进行升序排序
        bubbleSort(a.length);

        System.out.print("result: ");
        int zeroPos = findLastZero(0);
        System.out.print(zeroPos);

        sc.close();
    }
}

测试用例验证

  • 输入2,3,4 → 排序后[2,3,4] → 输出0(正确)
  • 输入0,1,2 → 排序后[0,1,2] → 输出1(正确)
  • 输入1,2,0 → 排序后[0,1,2] → 输出1(正确)
  • 输入2,0,0 → 排序后[0,0,2] → 输出2(正确)

内容的提问来源于stack exchange,提问作者Daniels Kikste-Zanders

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 04:31:05