0

I'm working on a project and we have a .txt file that looks like that :

0 4 8 4 8
0 4 4 1 8
5 6 2 1 0

Then I would like to read it and add it to my 2D ArrayList but I've failed multiple times (exceptions etc..)

I have a method that adds a whole line of Double to the ArrayList but the thing is I don't know how to read the file, check if there is a "line separator", if there is one re-read the line then convert each numbers found to Double and then add the Doubles to my 2D ArrayList with my addLine method.

I've tried so many things and here's the latest try i've done :

    public static Matrice lectureMatrice(String fileName) {
    //this is the matrix we will fill with the lines
    Matrice mat = null;
    //this is the newLine ArrayList we will fill then add
    List<Double> nouvelleLigne = new ArrayList<Double>();
    Double element = null;
    File file = new File(fileName + ".txt");
    try (Scanner scan = new Scanner(new FileReader(file))){
        while(scan.hasNextDouble()) {
            element = scan.nextDouble();
            nouvelleLigne.add(element);

        }
        //adding the whole line to the matrix
        mat.ajouterLigne(nouvelleLigne);
    } catch (FileNotFoundException e) {

        e.printStackTrace();
    } catch (ContrainteDoublonListeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

    return mat;
}
Roku
  • 35
  • 7
  • Use two Scanner objects, fileScanner to read in each `nextLine()` from the file and a lineScanner that you create within the while loop and feed in the line obtained from the fileScanner. In the 2nd scanner, the lineScanner, get your doubles, and dispose of it when done with it *in the loop*. – Hovercraft Full Of Eels Nov 30 '17 at 21:41
  • Again, use two scanners. The fileScanner loops in a while loop on `.hasNextLine()` and gets the line within the loop via `.nextLine()`. **That's** your line break. The second Scanner takes that line and parses the doubles. – Hovercraft Full Of Eels Nov 30 '17 at 21:51

0 Answers0