Home > Back-end >  How to print these csv file in a specific format?
How to print these csv file in a specific format?

Time:11-26

I'm just trying to print the csv file in the format shown below. How do I do that?


csv file - history,A,math,B,chemistry,A,geo,C,

art,B,literature,A,history,C,physics,A

public class readCsv (){
   public static void main (String [] args){
       String path = "file.csv";
       Scanner in = new Scanner (new FileReader (path));
       while (in.hasNextLine()){
          String string = in.nextLine();
          String [] token = string.split(",");
          String class = token [0]   token [2]   token [4]   token [6] ;
          String grade = token [1]   token [3]   token [5]   token [7];
          
         //prints the output
          System.out.print(class   grade);
   }
}

Current output - history math chemistry geo art literature history physics ABACBACA


Desired output -

History - A

Math - B

Chemistry - A

Geo - C


and so on....

CodePudding user response:

String class = token [0]   token [2]   token [4]   token [6] ;
String grade = token [1]   token [3]   token [5]   token [7];

This is your problem. You should create 2 arrays, one for Class and one for Grade. Since the class is on even places and grade is on odd, you should loop through the token array and check the index of each item. If the index is even, push the item token[index] to the Class array. If it is odd, push it to the Grade array. Then loop through one of the arrays and simply print Class[index] - Grade[index]. Here is some pseudocode.

Array Class
Array Grade

for i=0, i < length of array token (token.length?), i  
     if i % 2 == 0
         add token[i] to class
     else 
         add token[i] to grade 

for i=0 i < length of array grade (or class), i  
     console.out(class[i] - grade[i]

What happens is you get Array Class = [History, Math] and Array Grade = [A, B] (example values). You then loop through one of the arrays and since they are equal length, index 0 of array Class and index 0 of array Grade are History and A. Then you just print them.

CodePudding user response:

Again concatenating the tokens ( ) will have the commas removed.

for (int i = 0; i < token.length/2;   i) {
    System.out.println(token[2*i]   " - "   token[2*i   1]);
}

println prints a newline at the end, and just then you will see the output.

Every token pair of class and grade go with an even/odd index.

  • Related