将两个整型数组到Java的一个阵列 [英] Combine two integer arrays into one array in java

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

问题描述

我已经看到了类似的问题,并没有提供我正在寻找的答案,因此,如果这被认为是重复的我提前道歉。
我试图阵列组合{1,2​​,3}和{4,5,6}到{1,2,3,4,5,6}。我在做什么错误?我超级对Java。很抱歉,如果这个问题是愚蠢的。

 公共类结合{
  公共静态无效的主要(字串[] args){  INT []一个= {1,2,3};
  INT [] B = {4,5,6};
  INT [] C =新INT [A + B]。
  的for(int i = 0; I<则为a.length;我++)
  System.out.print(C [I] +);
}
公共静态INT []合并(INT []一,INT [] B){
  INT [] C =新INT [则为a.length + b.length个]
  INT I;
  对于(i = 0; I<则为a.length;我++)
     C [i] = a [i];     对于(INT J = 0; J< b.length个; J ++)
        C [我++] = B [J]。
        返回℃;
}
}


解决方案

而不是

  INT [] C =新INT [A + B]。

您需要调用你的合并方法和结果分配给像数组:

  INT [C =合并(A,B);

另外你的循环应该是:

  INT [C =合并(A,B);
的for(int i = 0; I< c.length;我++)
    System.out.print(C [I] +);

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;
}
}

解决方案

Instead of

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);

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天全站免登陆