0

i'm making a program that views a text file and prints it to the console in eclipse. One of the lines in the text file looks like this...

A.Matthews 4 7 3 10 14 50

when running the program, I get an error like this.. enter image description here

and this is the program

import java.io.*;    // for File
import java.util.*;  // for Scanner

public class MapleLeafLab {
public static void main(String[] args) throws FileNotFoundException {
    Scanner input = new Scanner(new File("mapleleafscoring.txt"));
    while (input.hasNextLine()) {
        String line = input.nextLine();
        Scanner lineScan = new Scanner(line);
        String name = lineScan.next(); // e.g. "Eric"
        String rest = lineScan.next();
        int GP = lineScan.nextInt();          // e.g. 456
        int G = lineScan.nextInt();
        int A = lineScan.nextInt();
        int P = lineScan.nextInt();
        int S = lineScan.nextInt();
        Double SS = lineScan.nextDouble();



        System.out.println(name+rest+" "+GP+" "+G+" "+A+" "+P+" "+S+" "+SS);

        //System.out.println(name + " (ID#" + id + ") worked " +
        // sum + " hours (" + average + " hours/day)");

    }
}
}
3
  • Not sure if that's the cause. But you don't need to define new Scanners inside the loop. One solution can be to read the file line by line and then use split to separate items in each line. Commented Oct 14, 2018 at 4:27
  • Unrelated: please read about java naming conventions. Variable names go camelCase. And if you want human readers, avoid using single character names. They are beyond meaningless. Commented Oct 14, 2018 at 4:35
  • Please read no pictures of exceptions / no pictures of code. Then use the edit link to replace screen shots of text with nicely formatted/indented text within your question. Commented Oct 14, 2018 at 4:37

1 Answer 1

1

Here's the Javadoc for Scanner:

https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

public double nextDouble()

Scans the next token of the input as a double... If the next token matches the Float regular expression defined above then the token is converted into a double value...

Returns:
    the double scanned from the input 
Throws:
    InputMismatchException - if the next token does not match the Float regular expression, or is out of range
    NoSuchElementException - if the input is exhausted
    IllegalStateException - if this scanner is closed

You're getting NoSuchElementException because you're trying to read 8 tokens from a 7-token line.

A.Matthews => name
4 => rest
7 => GP 
3 => G 
10 => A 
14 => P 
50 => S
SS =>  NoSuchElementException
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.