前言:这是我的一个班级的作业。
我需要通过CSV文件进行解析,并将每个字符串添加到ArrayList,以便我可以使用预先编码的函数单独与每个字符串进行交互。
我的问题是每行中的最后一个字符串(不以逗号结尾)与下一行中的第一个字符串组合在一起,并在ArrayList中被识别为位于同一索引处。我需要学习如何添加换行符或执行其他操作,以在每行末尾停止循环并单独读取下一行。也许在扫描仪类中有一个我不知道的内置方法为我做了这件事?感谢帮助!
以下是CSV文件中的信息:
Fname,Lname,CompanyName,Balance,InterestRate,AccountInception
Sally,Sellers,Seashells Down By The Seashore,100.36,3,7/16/2002
Michael,Jordan,Jordan Inc.,1000000000,3,6/12/1998
Ignatio,Freely,Penultimate Designs,2300.76,2.4,3/13/1991
到目前为止,这是我的代码
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class InterestCalculator {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("smalltestdata-sallysellers.csv"));
// Chomp off at each new line, then add to array or arraylist
scanner.useDelimiter("\n");
ArrayList<String> data = new ArrayList<String>();
while (scanner.hasNext()) {
// Grab data between commas to add to ArrayList
scanner.useDelimiter(",");
// Add grabbed data to ArrayList
data.add(scanner.next());
}
System.out.println(data.get(10));
scanner.close();
}
}
这是输出结果
7/16/2002
Michael
看起来你只需要做…
String s[] = scanner.nextLine().split(",");
Collections.addAll(data, s);