java - Finde positive and negative numbers from Array? -
i have 1 assignment , need . int[] array={12,23,-22,043,545,-4,-55,43,12,0,-99,-87} , must make 2 array. first positive , second negative , duplicate nubers . can not use arraylist.
int[] array={12,23,-22,0,43,545,-4,-55,43,12,0,-999,-87};
for(int i=0;i<array.length;i++){ if(array[i]>0){ system.out.println("positive:"+array[i]); } else if (array[i]<0){ system.out.println("negative:"+array[i]); } (int j = + 1; j < array.length; j++) { if (array[j] ==array[i]) { system.out.println("dup:"+array[j]); } } } }
res is:run: postive:12 dupli:12 postive:23 negative:-22 dupli:0 postive:43 dupli:43 postive:545 negative:-4 negative:-55 postive:43 postive:12 negative:-999 negative:-87 build successful (total time: 0 seconds) don know how postive: 12,23,0,43,545, etc.
try understand code , answer professor,
int[] array={12,23,-22,043,545,-4,-55,43,12,0,-99,-87}; list<integer> postivenumbers=new arraylist<integer>(); list<integer> negativenumbers=new arraylist<integer>(); list<integer> duplicatenumbers=new arraylist<integer>(); for(int i=0;i<array.length;i++){ if(!(postivenumbers.contains(array[i])||negativenumbers.contains(array[i]))) {//checks whether contains duplicates if (array[i] >= 0) { postivenumbers.add(array[i]); } else if (array[i] < 0) { negativenumbers.add(array[i]); } } else duplicatenumbers.add(array[i]); } system.out.println(postivenumbers); system.out.println(negativenumbers); system.out.println(duplicatenumbers);
Comments
Post a Comment