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

Java合并两个Scanner输入数组排序时新数组末尾输出0问题

问题根因

你的代码存在两个核心问题:

  • 双指针合并逻辑仅处理了两个数组同时有未遍历元素的场景,当其中一个数组遍历完成后,另一个数组剩余的元素没有被追加到结果数组中,int类型数组初始化时默认值为0,因此末尾会出现多余的0
  • 当前的双指针合并逻辑仅适用于两个输入数组本身已经按升序排序的场景,如果输入的数组是乱序的,最终合并结果也会不符合升序要求

修复方案

首先在原有while(i < n && j < m)循环结束后,追加两段逻辑,把剩余数组元素补入结果数组:

// 补入第一个数组剩余元素
while(i < n) {
    res[k] = ffinal[i];
    i++;
    k++;
}
// 补入第二个数组剩余元素
while(j < m) {
    res[k] = sfinal[j];
    j++;
    k++;
}

如果需要支持输入任意顺序的数组,最终合并后统一升序,可以简化逻辑,直接合并后排序:

// 把两个数组的元素全部放入结果数组
System.arraycopy(ffinal, 0, res, 0, n);
System.arraycopy(sfinal, 0, res, n, m);
// 直接排序
Arrays.sort(res);

修正后完整代码

import java.util.*;
 
public class Main
{
   public static void main(String[] args) 
   {
      Scanner x = new Scanner (System.in);
      System.out.print("Enter the number of elements of the first array: ");
      int first = x.nextInt();
      int ffinal[] = new int[first];

      for(int i=0;i<ffinal.length;i++)
      {
         ffinal[i]=x.nextInt();
      }

      System.out.print("Enter the number of elements of the second array: ");
      int second = x.nextInt();
      int sfinal[] = new int[second];

      for(int i=0;i<sfinal.length;i++)
      {
         sfinal[i]=x.nextInt();
      }
      
      int n = ffinal.length;
      int m = sfinal.length;

      int res[] = new int [n+m];

      int i = 0, j=0, k=0;
      while(i< n && j<m )
      {
         if(ffinal[i] <= sfinal[j])
         {
            res[k]=ffinal[i];
            i+=1;
            k+=1;
         }
         else
         {
            res[k]=sfinal[j];
            j+=1;
            k+=1;
         }
      }
      // 补入剩余元素
      while(i < n) {
          res[k] = ffinal[i];
          i++;
          k++;
      }
      while(j < m) {
          res[k] = sfinal[j];
          j++;
          k++;
      }
   
      System.out.print("New array:");
      for (i=0; i<n+m;i++)
      {
         System.out.print(" "+res[i]); 
      }
    
   }
}

内容的提问来源于stack exchange,提问作者sotanghoon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:24:03