java - How to remove unwanted elements in an array? -


in method below, i'm trying remove values in array input less 0 , greater 9. i've been doing research , found using arraylist.remove() best way not familiar yet. did try copy whole array "garbage" array , put values less 0 , greater 9. output still comes out 123145123145-110?

 public static void test (){  int[] input = {1,2,3,1,4,5,1,2,3,1,4,5,-1,10};      int[] garbage = new int[input.length];     (int i=0; i<input.length; i++){         if (input[i] < 0 && input[i] > 9){             garbage[i] = input[i];         }         int x = input[i];         system.out.print(x);   } 

//edit

  public static void votes(){      int[] input = {1,2,3,1,4,5,1,2,3,1,4,5,-1,10,20};         int count = 0;         int[] garbage = new int[input.length];         (int i=0; i<input.length; i++){             if (input[i]<0){                 garbage[count] = input[i];                 i++;                 count++;             }         int x = input[i];         system.out.print(x);          }    } 

you using wrong interval.

if (input[i] < 0 && input[i] > 9) 

should this

if (input[i] < 0 || input[i] > 9) 

your garbage should empty, syso.println shows elements in input array anyway. problem have elements 0 <= input[i] <= 9 in garbage array , lot of zeros between them, if use same index both arrays. in code should this

int[] garbage = new int[input.length]; int j = 0; (int i=0; < input.length; i++){     if (input[i] >= 0 && input[i] <= 9){         garbage[j] = input[i];         j++;         system.out.print(garbage[j]);     } 

}

this way see element added garbage. , zeros @ end of array.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -