Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何用多个数字连接数组_Java_Arrays_Integer_Int_Concatenation - Fatal编程技术网

Java 如何用多个数字连接数组

Java 如何用多个数字连接数组,java,arrays,integer,int,concatenation,Java,Arrays,Integer,Int,Concatenation,当我得到像[1,1,2,2,3,3,4]这样的数组时,我需要打印[1,2,3,4] 其他例子: 输入=[1,1,1,2]输出应=[1,2] 输入=[1,1,1,1]输出应为=[1] int count=1; //This for counts only the different numbers of the array input. for(int i=0; i<array.length-1;i++){ if(array[i+1]!=array[i]){

当我得到像[1,1,2,2,3,3,4]这样的数组时,我需要打印[1,2,3,4]

其他例子:

输入=[1,1,1,2]输出应=[1,2]

输入=[1,1,1,1]输出应为=[1]

 int count=1;
 //This for counts only the different numbers of the array input.
 for(int i=0; i<array.length-1;i++){
            if(array[i+1]!=array[i]){
                count++;

            }
        }
        //New array only for the needed numbers.
        Integer [] res = new Integer[count];
        res[0] = array[0];
        for(int i = 1;i<count;i++){
            if(array[i]!=array[i+1]){
                res[i]=array[i+1];
            }
        }
int count=1;
//这仅统计阵列输入的不同数目。

对于(int i=0;i一个问题是,即使在
array[i]==array[i+1]
时,也会增加循环的计数器,这会导致输出数组具有
null

另一个问题是在第二个循环中没有迭代输入数组的所有元素

如果使用两个索引,一个用于输入数组(循环变量),另一个用于输出数组中的当前位置,则两个问题都可以解决:

int count=1;
for(int i=0; i<array.length-1;i++){
    if(array[i+1]!=array[i]){
        count++;
    }
}
Integer [] res = new Integer[count];
res[0] = array[0];
int resIndex = 1;
for(int i = 1; i < array.length - 1; i++){
    if(array[i] != array[i+1]) {
        res[resIndex] = array[i+1];
        resIndex++;
    }
}
int count=1;

对于(int i=0;i可能重复的错误在
res[i]=array[i+1];
行中。您能找出这一行应该是什么,以及为什么吗?感谢dude做得很好。+++在某些情况下,条件
resIndex
可能会更早地打破循环。
for(int i = 1 ; i < array.length - 1 && resIndex < count; i++)