简体   繁体   中英

printing out csv file in specific format?

I'm reading from a csv file which has this layout:

CS4092,B
CS2013,A
CS8291,C
CS0927,D
CS0281,A

When I do print it out, I get this output:

CS4092
BMA4042
CCS4023
ACS4075
BCS4010
A

The output I'm trying to achieve is:

CS4092 - B
CS2013 - A
CS8291 - C
CS0927 - D
CS0281 - A

Can someone please tell me what way I can get the desired output. Thanks.

public class Student
{
    private String studentID;

public Student()
{

}
    public void setID(String studentID)
    {
        this.studentID = studentID;
    }
public void checkResults() throws IOException 
{
    String lines = "", unparsedFile = "", myArray[];
    String path = System.getProperty("user.home") + 
                             "/NetBeansProjects/CS4013Project/src/" +
                             this.studentID + "Results.csv";
    FileReader fr = new FileReader(path);
    try (BufferedReader br = new BufferedReader(fr)) 
    {
        while((lines = br.readLine()) != null)
        {
            unparsedFile += lines;
        }
    }
   myArray = unparsedFile.split(",");

   for(String item : myArray)
   {
       System.out.println(item);
  }
 }
}

You need to insert a comma between each pair of lines as you concatenate them to form unparsedFile.

Without that, unparsedFile contains:

CS4092,BCS2013,ACS8291,CCS0927,DCS0281,A

You need it to contain:

CS4092,B,CS2013,A,CS8291,C,CS0927,D,CS0281,A

    int i = 0;
    for (String item : myArray)
    {

        System.out.print(item);//It doent add a new line after printing the item
        if (++i % 2 != 0)
        {
            System.out.println(("-")); //if just one printed just append -
        }
        else
        {
            System.out.println(); //else put a new line and reset the flag
            i=0;

        }
    }

You are concatenating all the lines together (without newline separators). You should instead create an ArrayList<String> of lines and then split each of those.

Or use a CSV processing library.

Try replacing the while loop with:

while ((lines = br.readLine()) != null) {
   String myarray[] = lines.split(",");
   System.out.format("%s - %s\n", myarray[1],myarray[0]);
}

And remove the code after this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM