Java实现数组第二大数字查找方法输出0问题排查
问题描述
练习Java封装方法实现数组第二大值查找功能时,传入测试数组{1,3,2,5,3}预期返回结果3,实际运行始终输出0,多轮排查未定位错误。本次练习目标为掌握Java自定义方法的编写规则,不采用无封装的直接实现方案,原始代码如下:
public class App { public static int second(int a[],int n) { int[] arr = new int [n]; int temp; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { if(arr[i] > arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } return arr[n-2]; } public static void main(String[] args) { int[] arr = {1,3,2,5,3}; int n = 5; int result = second(arr,n); System.out.println(result); } }
错误定位
代码逻辑的核心漏洞在second方法的数组初始化环节:
- 方法内部通过
new int[n]声明了全新的局部数组arr,Java中int类型数组实例化后所有元素默认填充为0,后续冒泡排序的所有比较、交换操作都在这个全0数组上执行,始终没有将传入的形参数组a的元素复制到arr中,最终返回arr[n-2]自然得到0。
修复方案
在局部数组创建完成后,补充形参数组到局部数组的元素拷贝逻辑即可,最小改动的可运行版本如下:
public class App { public static int second(int a[],int n) { int[] arr = new int [n]; // 补全数组元素拷贝逻辑 for (int i = 0; i < n; i++) { arr[i] = a[i]; } int temp; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { if(arr[i] > arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } return arr[n-2]; } public static void main(String[] args) { int[] arr = {1,3,2,5,3}; int n = 5; int result = second(arr,n); System.out.println(result); } }
执行修复后的代码将正确输出3。如果不需要保留原数组的原始顺序,也可以直接在形参a上执行排序,省去新建数组和拷贝的额外开销。
内容的提问来源于stack exchange,提问作者Nuva_rad
相关产品推荐
相关产品推荐

