Exception in thread "main" java.util.NoSuchElementException

2

I have the following java method that reads a text file and creates new dots (coordinates in a graphic), however I am encountering the error of the title in reading the file. By following my stackTrace it points out that the error is when I try to read the first nextDouble (). Another curious thing is that sometimes it works normally, so I try to increase the number of points in my text file and it starts to freak out.

public void readDatabase(String s) throws FileNotFoundException{    
    try {               
        BufferedReader br = new BufferedReader(new FileReader(s));
        String line = br.readLine();
        Scanner trainFile = null;
        while (line != null) {      
            line.trim();
            trainFile = new Scanner(line);
            double x = trainFile.nextDouble();
            double y = trainFile.nextDouble();
            int type = trainFile.nextInt();
            this.database.add(new Ponto(x,y,type));
            line = br.readLine();
        }   
        trainFile.close();
        br.close();
    }
    catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

Does anyone have any idea what the problem is?

    
asked by anonymous 19.06.2014 / 03:45

2 answers

0

To solve the problem I made the following I changed the reading conditions of the next line in my code, this way I did not come across invalid lines.

public void readDatabase(String s) throws FileNotFoundException{    
    try {               
        final BufferedReader br = new BufferedReader(new FileReader(s));
        final Scanner trainFile = new Scanner(br);
        while (trainFile.hasNextDouble()) {      
            double x = trainFile.nextDouble();
            double y = trainFile.nextDouble();
            int type = trainFile.nextInt();
            this.database.add(new Ponto(x,y,type));
        }   
        trainFile.close();
        br.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}
    
27.06.2014 / 16:36
2

Are there any empty lines in your file? (the latter perhaps) A getDouble documentation % says:

  

NoSuchElementException - if the input is exhausted

I notice that you do trim on the line and go on to read via Scanner , without checking if that line is empty. I suggest doing this, and if so, proceed with the loop:

  while (line != null) {        
      line = line.trim(); // Nota: Strings são imutáveis - é preciso reatribuir o valor após o trim
      if ( line.length() == 0 )
          continue;
      trainFile = new Scanner(line);
      ...
    
19.06.2014 / 04:15