2

I want to write a code for removing some column from csv file. There is a csv file that contains rows and columns. I want to search for columns that have a zero number in first line and remove them and build a new csv file. I tried to write a csv file to array of string and after that searching in first row of array.

If there was a zero in a column, remove it. and at last build a new csv file.

Here is my code:

       public class removezero {
       public static void main(String[] args) throws Exception {

     //scanner to read csv file
    Scanner replace = new Scanner(new    File("csvfile"));


//array of string
 String [][] all= new String [5][5];

//new csv file to write answer
 FileWriter removezero = new FileWriter(createReplacedCsv());

 int i=0;
    StringBuilder builder = new StringBuilder();

 //write csv to array




while (replace.hasNext()) {

            String[] result = replace.nextLine().split(",");

            all[i]= result;
            i++;


        }


   // write from  array to builder

for(int j=0;j<5; j++){
for(int k=0;k<5; k++)
if(!(all[1][k]).equals("0")){builder.append(all[j][k]).append(",");}
builder.deleteCharAt(builder.lastIndexOf(","));
builder.append("\n");
}


 //write to csv file
  removezero.write(builder.toString());
  removezero.flush();
  removezero.close();

   }




 private static File createReplacedCsv() throws Exception {
 File replacedCsv = new File("removedzero.csv");
 replacedCsv.createNewFile();
 return replacedCsv;
    }


   }
user3496654
  • 101
  • 1
  • 3
  • 10

1 Answers1

0

The problem with your code is a consequence of the following line:

int col = replace.nextLine().length();

Since Scanner is a one way iterator (see here for more details: Using scanner.nextLine()) the extra call you perform to get the number of columns means that when reading CSV file in a loop you've got less elements than expected by countLines and you get an error by calling nextLine on empty iterator.

Community
  • 1
  • 1
Norbert Radyk
  • 2,532
  • 14
  • 23