0

I'm trying to make an application that reads a file and writes the sum of the numbers, the average, the number of numbers in the file, but I get an error

Exception in thread "main" java.util.InputMismatchException
t java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at TestGradesAnalysis.main(TestGradesAnalysis.java:30)
Java Result: 1

Can you help me fix the error?

import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.FileReader;
import java.io.*;

public class TestGradesAnalysis {

     public static void main(String args[]) throws IOException {


        PrintWriter outFile = new PrintWriter(new FileWriter("File.dat"));
        double sum = 0;
        int count = 0;
        double max = 0;
        double min = 0;

        while (in.hasNextDouble()) {
            sum = sum + in.nextInt();
            count++;
            if (in.nextDouble() > max) {
                max = in.nextDouble();

            }
            if (min > in.nextDouble()) {
                min = in.nextDouble();
            }
        }

        double average = sum / count;

        outFile.println("average is" + average);
        outFile.println("max is" + max);
        outFile.println("min is " + min);
        outFile.println("number of grades is" + count);

    }

This is my code

These are the contents of the File.dat

28 28 28 2008 510 September 89, 2116

1
  • Just for the completeness of the question - could you please post an input file (myDataFile.dat) example as well? Commented Nov 29, 2014 at 21:34

2 Answers 2

1

In the while loop you are calling nextDouble() multiple times. Meaning that even if hasNextDouble() is true, you advance several fields in one iteration a probably try to parse the September String as double at some point.

The solution would be to read the value once in every iteration and storing it in a variable.

while (in.hasNextDouble()) {
    double current = in.nextDouble();
    sum = sum + current;
    count++;

   if (current > max) {
       max = current;
   }
   if (min > current) {
       min = current;
   }
}
Sign up to request clarification or add additional context in comments.

9 Comments

After doing that, I cannot print to the file
How can I program java to create a text file and then print to that text file?
You have to call outFile.flush() as mentioned in this answer.
@ValterStrods how would I find the minimum value in the set of integers?
@CrazyRaisans max = Double.MIN_VALUE and min = Double.MAX_VALUE should do the trick.
|
0

There are a few things going wrong, but we start by focusing on the original question about the reported failure.

Misuse of Scanner.next()

The Scanner.next*() methods check the next token. This means that when you call them multiple times in your while loop, you will advance the list faster than what you probably want. We can fix this by calling it once at the start of the loop and holding on to the value.

Stopping at "April"

I am not completely sure of your requirements so I am not even sure if this needs to be fixed or what behaviour would be expected, but keep in mind the number reading from the input file will stop at the word "April". This is due for it checking whether there are any doubles (floating point numbers) coming up. That is false for a word/string (such as "April"). You could make the code advance by checking the generic hasNext() in combination with next() for a set amount of times if you so desire.

Missing output in the output file

You may or may not miss out on any output. The file will get created rather fast, but the writing might not happen. This is caused then by the program finishing before the writer can flush the stream. You should call PrintWriter.flush() after doing your println calls to inform the system it should flush the stream.

From the documentation for OutputStream.flush():

The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

The output file may not be in the correct directory

As you create the FileWriter with just a filename, I am not fully sure if you want to create it at the current working directory or not. I presume it is unintentional, in which case the filename provided should be dir + "/myDataFile.dat" instead.

Faulty minimum/maximum output values

You should set max as Double.MIN_VALUE and min as Double.MAX_VALUE when initializing those values. You will already see the minimum value not being set properly in your example - this is caused by the minimum value being 0 all the time already. You would see the maximum value not being set properly with your current code all of a sudden if all your values were actually negative (lower than 0).

Comments

Your Answer

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