The assignment given was, write a program that reads numbers off of a file, construct an array from those numbers, and move all the zeroes to the end of the array.
For example.
Before: 0, 9, 7, 0, 0, 23, 4, 0
After: 9, 7, 23, 4, 0, 0, 0, 0
After toying with it for about 2 hours i came up with this.
import java.io.*;
import java.util.Scanner;
public class Compactor{
Scanner in;
private int numNum = 0;
public void calcNumNum(){
try{
in = new Scanner(new File("compact.txt"));
while(in.hasNext()){
int dumpVal = in.nextInt();
numNum++;
}
makeArray(numNum);
}catch(IOException i){
System.out.println("Error: " + i.getMessage());
}
}
private void makeArray(int x){
int i = 0;
int[] arrayName = new int[x];
try{
in = new Scanner(new File("compact.txt"));
while(i < x){
arrayName[i] = in.nextInt();
i++;
}
compact(arrayName);
}catch(IOException e){
System.out.println("Error: " + e.getMessage());
}
}
private void compact(int[] x){
int counter = 0;
int bCounter = (x.length - 1);
for(int j = 0; j < x.length; j++){
if(x[j]!=0){
x[counter] = x[j];
counter++;
}else{
x[bCounter] = x[j];
bCounter--;
}
}
printArray(x);
}
private void printArray(int[] m){
int count = 0;
while(count < m.length){
System.out.print(m[count] + " ");
count++;
}
}
}
The file that was given to us was: 0, 6, 13, 0, 0, 75, 33, 0, 0, 0, 4, 2,9 21, 0, 86, 0, 32, 66, 0, 0.
What i got was: 6, 13, 75, 33, 4, 29, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0. (without the commas of course, i just put those in for easier reading.)
Could anyone perhaps give me insight on how to fix this problem, or maybe i should just start my code over with a different approach, the whole,
if(x[j]!=0){
x[counter] = x[j];
counter++;
}else{
x[bCounter] = x[j];
bCounter--;
}
i just made it up on the fly, thinking it would work fine, obviously it kept on going after it got past the last value and kept setting more and more values counting backwards as zeroes, no idea how to make it work though, any help would be greatly appreciated.
You’re almost there with
compact():