Not an ArrayList. An Array. For some reason, my teacher (or rather, the lesson plan we are using) requires that we make a program that takes an array of integers and removes all the zeroes. So far I have:

public void remove(int index) {
		
		for(int i = index; i < array.length - 1; i++) {
			array[i] = array[i + 1];
		}
	}
	
	public void compact() {
		
		readFile();
		
		System.out.print("Before: ");
		for(int i = 0; i < array.length; i++) {
			System.out.print(array[i] + " ");
		}
		
		System.out.println();
		for(int i = 0; i < array.length; i++) {
			if(array[i] == 0) {
				remove(i);
			}	
		}
		
		System.out.print("After: ");
		for(int i = 0; i < array.length; i++) {
			System.out.print(array[i] + " ");
		}
	}

However the output is:
Before: 0 94 12 21 3 0 0 34 26 44 55 0 32 0 0 0 0 0 0 0 0 0 0 0 0
After: 94 12 21 3 0 34 26 44 55 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

When it should be more like:

Before: 0, 9, 7, 0, 0, 23, 4, 0
After: 9, 7, 23, 4

I made all the errors in the output green so you don't have to weed them out.

Also, since I didn't comment it, I want to point out that remove() basically moves all the vales of the array once to the right if an undesired value is found (in this case, 0). I have determined that the error with the lone zero in the second line occurs because the remove() function simply moves all the values (including the second 0) to the right, and the second zero doesn't get checked. Does anyone have a solution for this?

And I need to find a way to remove all those trailing zeros without simply not printing them.

The readFile() function in compact() is there because the numbers of the array are supposed to come from a file.

The actual assignment can be found here.

Recommended Answers

All 14 Replies

The problem with your method is that the size of your array doesn't change. I would do this in your remove method:
1. create an array of size (original array size -1)
2. go through the original array one at a time.
3. If the index doesn't equal the index of the item being removed, add it to the new array.
4. return the new array.

There are probably more efficient solutions, but that will get the job done.

For some reason, I'm not allowed to do that. This is all supposed to be done with a single array.

this remove zeros...

for(int i = 0; i < array.length; i++) {

if(array[i] == 0) {
remove(i);


}

this remove zeros which is trailing of numbers like(90,100,)...

for(int i = 0; i < array.length; i++) {

if((array[i] %10)== 0) {
array[i]=(array[i] +"").replace("0","");




}

I think u can make use of the filter method that has been given here and it will return the filtered array without any zero's......
Think this will do the trick

public int[] filter(int[] arrNumbers){
	ArrayList arr = new ArrayList();
	for(int i=0;i<arrNumbers.length;i++){
		if(arrNumbers[i]!=0){
			arr.add(arr[i]);
		}
	}

	int retVal[] = new int[arr.size()];

	for(int i=0;i<retVal.length){
		retVal[i] = arr.get(i);
	}

	return retVal;
		

}

The problem can be solved using only one array in the following manner.

I have also fixed a bug in remove where the sequence that I have given below in array was not getting converted properly.

public class arrayMod 
{

   /*
       I have statically populated the array. Leaving that part to you
   */
	
	public static String array[]={"0", "94", "12", "21", "3", "0", "0" ,"34" ,"26", "44" ,"55", "0", "32", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "56","0","0","67"};


	
	public static void main(String[] args)
	{		
		
                           compact();
	}
	public static void remove(int index) 
	{
		
		for(int i = index; i < array.length -1 ; i++) 
		{
			array[i] = array[i + 1];
		}	
		array[array.length-1] = "";
		
	} 
	public static void compact()
	{
		
		System.out.println(array);
		
		System.out.print("Before: ");
		for(int i = 0; i < array.length; i++)
		{
			System.out.print(array[i] + " ");
		}		
		
		System.out.println();
		for(int i = 0; i < array.length; i++)
		{
			int j = i;
			
			while(array[i] == "0")
			{	
				
				remove(i);
					
				
				if(j == array.length)
				{
					break;
				}
				
				j++;
				
			}	
		}
			
		
		System.out.println();
		System.out.print("After: ");
		for(int i = 0; i < array.length; i++) 
		{
			System.out.print(array[i] + " ");
		}
	}
		
		
	

}

listen he asked

And I need to find a way to remove all those trailing zeros without simply not printing them

that i understood
input: 0,1,2,80,3,70,0,23
output:1,2,8,3,7,23

that's why i given the code like that in my reply...

^ No, that is not what he wanted. He just wants any 0's to be removed from the array. I thought I already answered this in another thread last week but in any case it's pretty simple so I don't understand why all of you guys are making it seem so complicated. In addition to the array, use one variable that contains the current size of the array. Then you just loop through the array and if there is a 0, you 'delete' it simply by replacing it with the next non-zero element in the array. So if you had

1, 2, 0, 4, 5 you'd end up with 1, 2, 4, 5, something (the something can be any value, but your size variable will hold 4 so you know the first 4 values in the array matter and the rest do not).

Shifting the non-zero values to the beginning of the array might be a bit trickier than it looks at first glance but it isn't hard.

I have done it by putting the array in a ArrayList.However I had to take the initial array as an Object[].

import java.util.ArrayList;
import java.util.List;

/* remove zeroes from an array without using another array
 *  
 *  use ArrayList, then
 *  
 * */
public class ArrRemoveElmZero 
{
  static Object[] arr = new Integer[]{1,40,45,0,39,780,0,3};
  
 
  
  public static void main(String[] args)
  {
	  ArrRemoveElmZero a = new ArrRemoveElmZero();
	  
	  arr = a.getElmsSanIndvZero();
	  
	 for(Object o:arr)
		 System.out.println((Integer)o);
	  
  }
  
  public Object[] getElmsSanIndvZero()
  {
	  List<Integer> l = new ArrayList<Integer>();
	  
	  for(Object obj:arr)
	  {
		if((Integer)obj != 0)
		{
	      	l.add((Integer)obj);	
		}
	  }
	  
	return l.toArray();
  }
  
}

Why is everybody handing out code snippets to the OP here ? Not to mention some of you have got the assignment wrong completely.

If you could see two of the more senior pros here have both given the solution without providing the code for it. Thats the way it should be done, you make him understand the solution by outlining steps using pseudocode, Simple English etc but I guess not many people here know that way.

PS: I don't know how and edit caused it to be posted twice, just ignore the next post of mine.

Why is everybody handing out code snippets to the OP here ? Since when did it became the most easiest way of giving solns ? Not to mention some of you have got the assignment wrong completely.

If you could see two of the more senior posters here have both given the solution without providing the code for it. Thats the way it should be done, you make him understand the solution by outlining steps using pseudocode, Simple English etc but I guess not many people here know that way.

I decided to take BestJew's advice, and makes a method that shifts all non-zero integers to the beginning of the array:

public void shift(int index) {
		
		// placeholder and h are instance variables, both initialized to 0
		
		placeholder = array[index];
		array[h] = placeholder;
		h++;
	}

But the output is now:

Before: 0 94 12 21 3 0 0 34 26 44 55 0 32 0 0 0 0 0 0 0 0 0 0 0 0
After: 94 12 21 3 34 26 44 55 32 44 55 0 32 0 0 0 0 0 0 0 0 0 0 0 0

Any suggestions? I've decided that the trailing zeroes are a problem I'll deal with later, first I want the actual compacting to work first.

Thanks to everyone for their feedback.

Never mind. I solved that problem by adding the line in green:

public void shift(int index) {
		
		// placeholder and h are instance variables, both initialized to 0
		
		placeholder = array[index];
		array[index] = 0;
		array[h] = placeholder;
		h++;
	}

to know this the correct program is

import java.util.*;
public class remove_zero
{
 void main()
 {
  Scanner ob=new Scanner(System.in);
  int a[]= new int[6],i;
  System.out.println("Enter the elements");
  for(i=0;i<6;i++)
  {
   a[i]=ob.nextInt();
   }

   int j=0;
   for( i=0;i<a.length;i++)
   {
    if(a[i]!=0)
    {
     a[j]=a[i];
     j++;
     }
     }
     System.out.println("The elements are");
     for( i=0;i<j;i++)
     System.out.println(a[i]);
     }
     }

Your "correct" progam fails to remove the zeros. It just overwrites them and stops printing before it gets to the original values left at the end of the array.
As for the quality of the code, including Java naming convention, formating and indentation, it's maybe some of the worst code I have seen.
To be kind, I'll give you 1/10 for trying.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.