2016-10-24 52 views
0

我試圖使用Scanner從CSV文件中讀取數據,但當我嘗試讀取最後一個double數據並且在CSV中存在多行時收到InputMismatchException文件。我認爲這是因爲它正在閱讀\ n作爲雙倍的一部分。我如何讓它忽略換行符?使用Scanner從文件中讀取時InputMismatchException

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; 
} 
+0

只是做的String []輸入= in.nexLIne()分裂( 「」),然後你會根據數組中的索引,您可以將數組 –

+0

的每個索引中的所有值都轉換爲Double或保留爲String –

回答

0
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 
      } 
     } 

    } 
相關問題