Java 将数组中的相同值合并在一起
它将成为:Java 将数组中的相同值合并在一起,java,arrays,Java,Arrays,它将成为: [go, go, go, go, go, go] [go, stop, stop, stop] 我该怎么做?我做错了什么?您需要更改上一个内部循环: [go (5)] [go (1), stop (3)] int count=0; 对于(int h=0;h位置;i--){ 移除温度(i); 位置=i-1; } 温度设置(位置,数组[f][g][h]+”(“+count+”)); } //计数在此之后不会重置,因此这将是错误的! } 我会怎么做: int coun
[go, go, go, go, go, go]
[go, stop, stop, stop]
我该怎么做?我做错了什么?您需要更改上一个内部循环:
[go (5)]
[go (1), stop (3)]
int count=0;
对于(int h=0;h位置;i--){
移除温度(i);
位置=i-1;
}
温度设置(位置,数组[f][g][h]+”(“+count+”));
}
//计数在此之后不会重置,因此这将是错误的!
}
我会怎么做:
int count = 0;
for (int h = 0; h < array[f][g].length; h++) {
if (array[f][g][h].equals(array[f][g][h+1])) count++;
//You dont check for out of bound here, so `h + 1` will cause out of bound error
else {
ArrayList<String> temp = new ArrayList<String>(Arrays.asList(array[f][g]));
for (int i = count - 1; i > position; i--) {
temp.remove(i);
position = i-1 ;
}
temp.set(position, array[f][g][h] + " (" + count + ")");
}
//Count is not reset after this, so this will be wrong!
}
ArrayList tmp=new ArrayList();
对于(int h=0;h
ArrayListtmp
将保存数组[f][g]
的结果,您应该注意我如何相应地更新h
以跳过所有相同的元素
更新:测试您可以从正确比较字符串开始(使用等于,而不是==)据我所知,阵列的两个外部维度与重复数据消除无关。如果是这种情况,考虑如何对
String[]
执行此操作可能会更容易,然后将对该方法的调用分成两个for循环,以迭代外部维度。@Eran哎呀。我修好了,但还是不行。我得到了一个ArrayIndexOutOfBoundsException
。我不明白你为什么需要一个3D数组!你能解释一下吗?我不知道。它之所以存在,是因为我在代码的不同部分使用了3D数组,所以保持它的原样很简单。Pham Trung下面的解决方案非常适合1D阵列。@CalvinKinzie抱歉,我无法查看链接(这是我的网络问题),但是,我已经测试了我的代码,结果是。所以我认为直接将其用于三维或更高维数组是很简单的,您不再需要使用位置:)啊,谢谢。我还意识到我的错误是我从来没有把数组[f][g]=tmp.toArray(新字符串[tmp.size()])代码>在代码中的结束括号之后(我建议添加该括号)。现在一切都好了。
int count = 0;
for (int h = 0; h < array[f][g].length; h++) {
if (array[f][g][h].equals(array[f][g][h+1])) count++;
//You dont check for out of bound here, so `h + 1` will cause out of bound error
else {
ArrayList<String> temp = new ArrayList<String>(Arrays.asList(array[f][g]));
for (int i = count - 1; i > position; i--) {
temp.remove(i);
position = i-1 ;
}
temp.set(position, array[f][g][h] + " (" + count + ")");
}
//Count is not reset after this, so this will be wrong!
}
ArrayList<String> tmp = new ArrayList<>();
for (int h = 0; h < array[f][g].length; h++) {
int count = 1;
while(h + count < array[f][g].length && array[f][g][h].equals(array[f][g][h+count]))
count++;
tmp.add(array[f][g][h] + "(" + count + ")");
h += count - 1;//Update h to skip identical element
}