[英]InputMismatchException when using Scanner to to read from a file
我正在嘗試使用掃描儀從CSV文件中讀取內容,但是當我嘗試讀取最后一個雙精度字符時,卻收到了InputMismatchException,並且我的CSV文件中有多行。 我認為這是因為它正在讀取\\ n作為double的一部分。 我如何才能忽略換行符?
CSV文件
P1,25,30
P2,10,10
爪哇
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;
}
while (in.hasNext())
{
String[] inputLine = in.nextLine().split(",");
//check that the line contains 3 comma seperated values
if(inputLine.length == 3)
{
String title = inputLine[0]; //first on should be P1, p2 etc
//catch the exception if we are unable to parse the two expected doubls
try
{
double mark = Double.parseDouble(inputLine[1]);
double outOf = Double.parseDouble(inputLine[2]); //Program Crashes here
//if we got here then we have valid inputs for adding a MarkEntry
entries.add(new MarkEntry(title, mark, outOf));
}catch(NumberFormatException er)
{
//print stack trace or something
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.