dcsimg
Arrays- How to remove zeros when they are in an array
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Quan_Tran
Posted On:   Monday, March 1, 2004 04:56 PM

Hello, I have a question that has to deal with arrays. Can anyone help me write a code where i have a inFile from a different location and I'm suppose to remove all the zeros for it. for example:
Before: 0,9,7,0,0,23,4,0
After: 9,7,23,4

Thanks!

Re: Arrays- How to remove zeros when they are in an array

Posted By:   David_Thornton  
Posted On:   Tuesday, March 2, 2004 05:12 PM

See example below;


/**
* @author David Thornton
*
*
*
*/
public class TestRemoveZeros {
public static void main(String args[]) {

int[] myArray = {0,9,7,0,0,23,4,0};
TestRemoveZeros tst = new TestRemoveZeros();

for (int i = 0; i < tst.removeZeros(myArray).length; i++) {
System.out.println(tst.removeZeros(myArray)[i]);
}
}

public int[] removeZeros(int[] inArray){
Vector wrkVector = new Vector();
for (int i = 0; i < inArray.length; i++) {
if (inArray[i] != 0){
wrkVector.addElement(new Integer(inArray[i]));
}
}
int [] outArray = new int[wrkVector.size()];
for (int j = 0; j < wrkVector.size(); j++) {
outArray[j] = ((Integer) wrkVector.elementAt(j)).intValue();
}
return outArray;
}

}

About | Sitemap | Contact