[英]InputMismatchException when using Scanner to to read from a file
I am trying to read from a CSV file using the Scanner but I am getting an InputMismatchException when I try and read the last double and are there is more than one line in my CSV file. 我正在尝试使用扫描仪从CSV文件中读取内容,但是当我尝试读取最后一个双精度字符时,却收到了InputMismatchException,并且我的CSV文件中有多行。 I think this is because it is reading \\n as part of the double.
我认为这是因为它正在读取\\ n作为double的一部分。 How do I get it to ignore the line break?
我如何才能忽略换行符?
CSV file 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;
}
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.