2016-10-24 1 views
0

J'essaie de lire à partir d'un fichier CSV en utilisant le scanner mais j'obtiens une exception InputMismatchException lorsque j'essaie de lire le dernier double et qu'il y a plus d'une ligne dans mon fichier CSV fichier. Je pense que c'est parce qu'il lit \ n dans le cadre du double. Comment l'obtenir pour ignorer le saut de ligne?InputMismatchException lors de l'utilisation de Scanner pour lire à partir d'un fichier

fichier 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

faire juste String [] = entrée in.nexLIne(). Split ("") et alors vous avoir toutes vos valeurs dans chaque index du tableau –

+0

basé sur l'index dans le tableau, vous pouvez convertir en double ou garder comme une chaîne –

Répondre

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

    }