我正在尝试使用扫描仪读取 CSV 文件,但当我尝试读取最后一个 double 值并且 CSV 文件中是否有多行时,我收到了一个 InputMismatchException 异常。我认为这是因为它正在读取\n 作为 double 的一部分。如何让它忽略换行符?
CSV 文件
P1,25,30
P2,10,10
Java
public static ArrayList<MarkEntry> readCSV(File file) {
ArrayList<MarkEntry> entries = new ArrayList<>();
try
{
Scanner in = new Scanner(file).useDelimiter(",");
while (in.hasNext())
{
String title = in.next();
double mark = in.nextDouble();
double outOf = in.nextDouble(); //Program Crashes here
entries.add(new MarkEntry(title, mark, outOf));
}
} catch (FileNotFoundException e)
{
System.out.println("File: " + file + " not found");
}
return entries;
}
最佳答案
您可以使用多个分隔符:
Scanner in = new Scanner(input).useDelimiter(",|\\r\\n");
注意:在 Linux 上,行结尾只是 \n
,因此您可以使用以下代码:
Scanner in = new Scanner(input).useDelimiter(",|\\n");
关于java - 当使用\n 从字符串中读取 double 值时,扫描仪会出现 InputMismatchException — Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40166849/