[英]Removing specific value from array (java)
我有整数a = 4和数组b 7,8,9,4,3,4,4,2,1
我必须编写一个从数组b中删除int ALL a的方法
期望的结果7,8,9,3,2,1
这是我到目前为止,
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
boolean[] barray = new boolean [array3.length];
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
int[] array4 = new int [array3.length - counter];
int num = 0;
for (int j=0; j<array3.length; j++)
{
if(barray[j] == false)
{
array4[num] = array3[j];
num++;
}
}
return array4;
我收到这个错误
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Utility.removeTwo(Utility.java:50)
at Utility.main(Utility.java:18)
Java结果:1
任何帮助将非常感激!
错误源于此for循环:
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
当你创建int[] array4 = new int [array3.length - counter];
您正在创建一个大小为0的数组。如果该项是要删除的项,则只应增加计数器:
for (int k=0; k<array3.length; k++)
{
boolean b = (x == array3[k]);
barray[k] = b;
if(b) {
counter++;
}
}
要在注释中回答您的问题,应该调用该方法,并且可以像这样检查:
public static void main(String[] args) {
int[] array3 = {0,1,3,2,3,0,3,1};
int x = 3;
int[] result = removeTwo(x, array3);
for (int n : result) {
System.out.print(""+ n + " ");
}
}
在这一行:
int[] array4 = new int [array3.length - counter];
您创建一个大小为0的数组,因为此时counter
等于array3.length
。
这意味着您无法访问该数组中的任何索引。
你正在创造
int[] array4 = new int [array3.length - counter];// 0 length array.
那里你不能有0th
索引。 至少长度应该为1
以具有0th
索引。
BTW我的建议,最好使用List
。 那么你可以轻松做到这一点。
真的是一个数组是这个工作的错误工具,因为除了其他任何东西你最终会得到你无法删除的杂散值。 只需使用ArrayList,它就可以提供removeAll()方法来完成您的需要。 如果你真的需要数组,你甚至可以这样做:
List<Integer> list = new ArrayList(Arrays.asList(array))
list.removeAll(4);
array = list.toArray();
(确切的方法名称/参数可能需要调整,因为这些都来自内存)。
最简单的方法是使用第二个数组放置正确的值
有点像
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
int[] array4 = new int[array3.lenght];
for (int i = 0; i < array3.lenght; i ++) {
if(array3[i] == x){
array4[counter] = array3[i];
}
}
return array4;
}
anoterh方法是从array3
删除x
calue并将值向前移动
从数组中删除元素的最佳方法是使用List
with Iterator
。 尝试,
Integer[] array = {7, 8, 9, 4, 3, 4, 4, 2, 1};
List<Integer> list = new ArrayList(Arrays.asList(array));
for(Iterator<Integer> it=list.iterator();it.hasNext();){
if(it.next()==4){
it.remove();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.