[英]Printing out specific data and calculations when multiple records in a CSV file
[英]printing out csv file in specific format?
我正在讀取具有以下布局的csv文件:
CS4092,B CS2013,A CS8291,C CS0927,D CS0281,A
當我打印出來時,得到以下輸出:
CS4092 BMA4042 CCS4023 ACS4075 BCS4010 A
我想要達到的輸出是:
CS4092 - B CS2013 - A CS8291 - C CS0927 - D CS0281 - A
有人可以告訴我我可以通過什么方式獲得所需的輸出。 謝謝。
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);
}
}
}
您需要在每對線之間插入逗號,以將它們連接起來形成unparsedFile。
否則,unparsedFile將包含:
CS4092,BCS2013,ACS8291,CCS0927,DCS0281,A
您需要包含以下內容:
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;
}
}
您正在將所有行連接在一起(沒有換行符)。 相反,您應該創建一個由行組成的ArrayList<String>
,然后拆分其中的每行。
或使用CSV處理庫。
嘗試將while循環替換為:
while ((lines = br.readLine()) != null) {
String myarray[] = lines.split(",");
System.out.format("%s - %s\n", myarray[1],myarray[0]);
}
然后刪除代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.