java中将两个整数数组合并为一个数组 [英] Combine two integer arrays into one array in java

查看:47
本文介绍了java中将两个整数数组合并为一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过类似的问题,但没有一个提供我正在寻找的答案,所以如果这被认为是重复的,我提前道歉.我正在尝试将数组 {1, 2, 3} 和 {4, 5, 6} 组合成 {1, 2, 3, 4, 5, 6}.我做错了什么?我是java的超级新手.对不起,如果这个问题很愚蠢.

I've seen similar questions and none provide the answer that I'm looking for, so I apologize in advance if this is considered a duplicate. I'm trying to combine arrays {1, 2, 3} and {4, 5, 6} into {1, 2, 3, 4, 5, 6}. What am I doing incorrectly? I'm super new to java. Sorry if the question is stupid.

public class combine {
  public static void main(String[]args){

  int[]a = {1, 2, 3};
  int[]b = {4, 5, 6};
  int[]c = new int[a+b];
  for(int i=0; i<a.length; i++)
  System.out.print(c[i]+" ");
}
public static int[]merge(int[]a, int[]b){
  int[]c = new int[a.length+b.length];
  int i;
  for(i=0; i<a.length; i++)
     c[i] = a[i];

     for(int j=0; j<b.length; j++)
        c[i++]=b[j];
        return c;
}
}

推荐答案

代替

int[]c = new int[a+b];

您需要调用合并方法并将结果分配给数组,例如:

You need to call your merge method and assign the result to the array like :

int[]c = merge(a,b);

你的 for 循环也应该是:

Also you for loop should be :

int[]c = merge(a,b);
for(int i=0; i<c.length; i++)
    System.out.print(c[i]+" ");

这篇关于java中将两个整数数组合并为一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆