impact_sv1
impact_sv1

Reputation: 13

Error while reading the last entry of a file

I am reading a file using a delimiter with a scanner. When I get to the last entry of the file it says I am out of bounds. If I count correctly I am in bounds though.

Here is the code and it is throwing an input mismatch error. Any help is appreciated. Thanks.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws IOException {
        String personName = null;
        double score = 0;

        File myFile = new File("twogrades.dat");

        try {
            Scanner scan = new Scanner(myFile).useDelimiter(",");

            while (scan.hasNext()) {
                personName = scan.next();

                for (int i = 0; i <= 5; i++) {
                    score += ((scan.nextDouble() / 50) * 0.03);
                }

                for (int i = 6; i <= 11; i++) {
                    score += ((scan.nextDouble() / 10) * 0.02);
                }
                score += ((scan.nextDouble()) * 0.20);
                score += ((scan.nextDouble()) * 0.50);

                PrintWriter out = new PrintWriter(new BufferedWriter(
                        new FileWriter("grades.dat", true)));
                out.println(personName + " " + score);

                out.close();
                score = 0;
                scan.nextLine();
            }

            scan.close();
        } catch (InputMismatchException e) {
            System.out.println(e.getMessage()
                    + " You entered a wrong data type");
        } catch (NoSuchElementException e) {
            System.out.println(e.getMessage()
                    + " There are no more elements left in the file");
        } catch (IllegalStateException e) {
            System.out.println(e.getMessage());
        }
    }
}

Here is the file

Yuri Allen,5,26,16,22,18,3,0,4,4,2,10,2,54,89

Upvotes: 0

Views: 87

Answers (2)

Stefan Dollase
Stefan Dollase

Reputation: 4620

I am able to reproduce the error, but only if there is more than one line in the input file. The problem is the delimiter. You only use the comma ",". Thus, the scanner tries to read the new line character with the last entry of the line: "89\n". Since this is not a valid double, you get the exception.

You can solve this by adding the new line character as a delimiter: ",|\\r\\n|\\r|\\n"

Upvotes: 1

T D Nguyen
T D Nguyen

Reputation: 7603

I run it and the result is: No line found There are no more elements left in the file and the output Yuri Allen 55.398. Possibly you can clean, rebuild your project and change:

while (scan.hasNext()) {

to this

while (scan.hasNextLine()) {

Upvotes: 0

Related Questions