我有一个任务,要创建一个采用字符串数组元素的方法,检查是否存在重复项,然后将其删除(我尝试用“ null”进行的操作),然后将所有其他元素移向索引值[0 ]来缩小差距。
现在看起来像这样:
public static boolean deleteTask() {
boolean removed = false;
for (int pos = 0; pos < todos.length; pos++) {
if (todos[pos].equals(titel)) {
todos[pos] = null;
removed = true;
if (removed){
//set pos+1 = pos to reduce each value -1.
//repeat process for each index [10]
}
}
}
return removed;
}
}
在图片中,我展示了看到的结果。例如pos.4是重复的-然后将其设置为null。现在,以下所有索引必须更改为-1才能填补空白。显然,然后将索引设置回456而不是567,这只是为了说明字符串的移动。
你能帮我[pos] null之后沿-1方向移动索引吗?
如果您可以帮忙完成2次以上的重复操作,那就更好了。
代替
todos[pos + 1] = todos[pos];
你应该使用
todos[pos] = todos[pos + 1];
这是工作代码:
public static boolean deleteTask() {
boolean removed = false;
for (int pos = 0; pos < todos.length; pos++) {
if (todos[pos].equals(titel)) {
todos[pos] = null;
removed = true;
}
if (removed && pos < todos.length - 1) {
// swap the string with the next one
// you can't do this with the last
// element because [pos + 1] will
// throw an indexoutofbounds exception
todos[pos] = todos[pos + 1];
} else if (removed && pos == todos.length - 1) {
// here you can swap the last one with null
todos[pos] = null;
}
}
return removed;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句