0

I wrote this code that was intended to read a file with integer values. If the integer values are >= 0 and <=100 I need to give the average of the grades. If there are any values out of the specified range 0-100 then I need to count the incorrect integer grades, inform the user of the incorrect grades, and inform how many incorrect grades there were. I attempted the code but I keep getting the error code:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Project9.main(Project9.java:26)

Code sample:

public static void main(String[] args) throws IOException{
    String file;
    int readInts;

    Scanner k = new Scanner(System.in);

    System.out.println("Enter filename: ");
    file = k.nextLine();
    int counterWrong = 0;
    int counterRight = 0;
    int sum = 0;
    double average = 1.0 * sum/counterRight;

    File fileReader = new File(file);

    if (fileReader.exists()) {
        Scanner input = new Scanner(fileReader);
        while (input.hasNext()) {
            readInts = input.nextInt();
            System.out.println(readInts);
            String a = input.next();
            int a2 = Integer.parseInt(a);

        if (a2 <= 100 && a2 >= 0){
            counterRight++;            
            sum = sum + a2; 
            System.out.println("Score " + a2 + " was counted.");

        } else {
            counterWrong++;
            System.out.println("The test grade " + a2 + " was not scored as it was out of the range of valid scores.");
            System.out.println("There were " + counterWrong + " invalid scores that were not counted.");
        }
        }
        if (counterRight > 0){
            System.out.println("The average of the correct grades on file is " + average + ".");
        }
    } else {
        System.out.println("The file " + file + " does not exist. The program will now close.");
    }


}

}

2
  • 1
    Please show us the file you are reading Commented Oct 15, 2015 at 17:30
  • you are reading 2 token in while loop but you only check hasNext() on one only Most prbably you dont have any token left in the file and you are still reading the file with input.next() put a check before this line also Commented Oct 15, 2015 at 17:32

3 Answers 3

1

You are doing a single check hasNext but then you read twice from scanner using nextInt() and next().

Sign up to request clarification or add additional context in comments.

Comments

0

There may be two issues with your code I see.

  1. file = k.nextLine(); // Depending on how your file is set up k.nextLine() or k.next() or maybe k.nextInt() may be useful.

  2. while (input.hasNext()) { readInts = input.nextInt(); // input.hasNext() assumes the next value the scanner is reading has a string value which would make readInts = input.nextInt(); impossible to use without parsing (or some other method).

I thought it'd be fun to try out this exercise (didn't want to ruin it for you). Check out my code and hopefully you'll pick up on some of the concepts I was talking about.

Note: My program reads integer values like 95 185 23 13 90 93 37 125 172 99 54 148 53 36 181 127 85 122 195 45 79 14 19 88 34 73 92 97 200 167 126 48 109 38. Which uses hasNext() & next() to get every token listed. So using nextLine() wouldn't be useful for the given input.

package cs1410;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import javax.swing.JFileChooser;

public class Grader {

    public static void main(String[] args) throws IOException {
        int count = 0;
        int sum = 0;
        double ave = 0;
        int incorrectCount = 0;
        String correctGrades = "";
        String incorrectGrades = "";

        // Read file input
        JFileChooser chooser = new JFileChooser();
        if (JFileChooser.APPROVE_OPTION != chooser.showOpenDialog(null)) {
            return;
        }
        File file = chooser.getSelectedFile();

        // Scan chosen document
        Scanner s = new Scanner(file);


        // While the document has an Int
        while (s.hasNextInt()) {
            // Convert our inputs into an int
            int grade = Integer.parseInt(s.next());

            if (grade >= 0 && grade <= 100) {
                // adds sum
                sum += grade;
                // increments correct count
                count++;
                // displays valid grades
                correctGrades += Integer.toString(grade) + "\n";
            } else {
                // increments incorrect count
                incorrectCount++;
                // displays invalid grades
                incorrectGrades += Integer.toString(grade) + "\n";
            }
        }
        // Created average variable 
        ave = sum / count;

        // bada bing bada boom
        System.out.println("The number of correct grades were " + correctGrades);
        System.out.println("The average score on this test was " + ave + "\n");
        System.out.println("The number of incorrect grades were " + incorrectCount + "\n");
        System.out.println("The incorrect values for the grades were " + "\n" + incorrectGrades);

    }

}

1 Comment

Perfect, thanks a ton. There is another step to my program that I am going to post as a new thread. My last question is more simple.
0

Use hasNextInt() instead of hasNext().

hasNext() only means there is another token, not necessarily that there is another integer which you are assuming when you wrote nextInt().

Here's the documentation for hasNext() and hasNextInt()

You also want to do a check before this line:

String a = input.next();

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.