Write a program that reads a text file (compact.txt) and stores the integers in an array. Your instructor will provide this text file.
Write a method compact that removes all zeroes from the array, leaving the order of the other elements unchanged. All local variables within this function must be scalar. In other words, you may not use a second array to solve the problem.
Do not solve the problem by printing out only the non-zero values in the array. The compact method must remove all zeros from the array.
Instructions:
Print out the list both before and after removing the zeros. For example:
Before: 0, 9, 7, 0, 0, 23, 4, 0
After: 9, 7, 23, 4
Your program must use proper modular design and parameter passing.
I made my program and I think I made it right, however it is only printing out the before line and not the after line where there are no zeros! My code is displayed below and my compact.txt file reads: 0 6 13 0 0 75 33 0 0 0 4 29 21 0 86 0 32 66 0 0. Could you please tell me where I am going wrong? Thank you for any help you can provide!
package chap;
import java.util.Scanner;
import java.io.*;
public class Compact{
public void printList(int[] list){
for(int index = 0; index < list.length; index++){
System.out.print(list[index]+" ");
}
System.out.println();
}
public int[] getArray(){
int value;
int count = 0;
int[] scannedArray = new int[getListSize()];
Scanner in;
try{
in = new Scanner(new File("Compact.txt"));
while(in.hasNextInt()){
value = in.nextInt();
scannedArray[count] = value;
count++;
}
}
catch(IOException z){
System.out.println("File Not Found");
}
return scannedArray;
}
public static int getListSize(){
int count = 0;
Scanner readText;
try{
readText = new Scanner(new File("Compact.txt"));
while(readText.hasNextInt()){
count++;
readText.nextInt();
}
}
catch(IOException z){
System.out.println("File not found");
}
return count;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Compact startingArray = new Compact();
startingArray.printList(startingArray.getArray());
}
}

New Topic/Question
Reply


MultiQuote




|