我只是想以如下所示的格式列印 csv 檔案。我怎么做?
.csv 檔案
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);
}
}
電流輸出-
history math chemistry geo art literature history physics ABACBACA
所需的輸出-
History - A
Math - B
Chemistry - A
Geo - C
等等....
uj5u.com熱心網友回復:
String class = token [0] token [2] token [4] token [6] ;
String grade = token [1] token [3] token [5] token [7];
這是你的問題。您應該創建 2 個陣列,一個用于 Class,一個用于 Grade。由于班級在偶數位置而成績在奇數位置,您應該回圈遍歷標記陣列并檢查每個專案的索引。如果索引為偶數,則將專案標記[index] 推送到 Class 陣列。如果是奇數,則將其推送到 Grade 陣列。然后回圈遍歷其中一個陣列并簡單地列印 Class[index] - Grade[index]。這是一些偽代碼。
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]
發生的情況是您得到 Array Class = [History, Math] 和 Array Grade = [A, B](示例值)。然后回圈遍歷其中一個陣列,因為它們的長度相等,陣列 Class 的索引 0 和陣列 Grade 的索引 0 是 History 和 A。然后你只需列印它們。
uj5u.com熱心網友回復:
再次連接標記 ( ) 將洗掉逗號。
for (int i = 0; i < token.length/2; i) {
System.out.println(token[2*i] " - " token[2*i 1]);
}
println 最后列印一個換行符,然后你就會看到輸出。
每個標記對的班級和年級都有一個偶數/奇數索引。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/368638.html
