[英]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.