I need to display the original information from the input file (see below) as it is presented, compute and display each player's average score on his respective line.

Input file:
Smith 13 20 8 12 -1
Burch 21 18 16 -1
John -1
Mike 5 -1

(FYI) -1 is the sentinal.

Error I am getting at runtime:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at stats.main(stats.java:29)

My code line 29 is at "score = infile.nextDouble();" under the first while statement.

Any help will be greatly appreciated. THANKS!

import java.util.Scanner;          //for reading input
import java.io.*;                  //for reading files

public class stats
{

	public static void main(String[]args) throws IOException
	{
	
	String name=null;
	double score=0, totalScore=0, count=0;
	double avg=0;

	File fin = new File("data.dat");
	Scanner infile = new Scanner(fin);

	while (infile.hasNext())
	{
		name = infile.nextLine();
		score = infile.nextDouble();

		while (score != -1)
		{
			System.out.print(name + " " + score + " ");
			totalScore = totalScore + score;
			score = infile.nextDouble();
			System.out.print(score + " ");
			count = count + 1; 
			avg = totalScore/count;
			System.out.print("Players average: " + avg);
			
		}

		System.out.println(" ");

	}
	}
}

The problem you see is here :-

name = infile.nextLine();
  score = infile.nextDouble();

infile.nextLine() would read the entire line of text in your file, So on your first iteration in the while, your "name" variable would contain "Smith 13 20 8 12 -1" and after that line the token position in your File would be as shown by "^" below.

Smith 13 20 8 12 -1
Burch 21 18 16 -1
^
John -1
Mike 5 -1

Now at this point when your token is currently pointing to "Burch", you call infile.nextDouble(); , So bang !!! an input mismatch, your program is expecting a double value but instead finds a "String" and hence the InputMismatchException.

You can solve this problem by using the next() method instead of the nextLine() method. You can read more about the Scanner class from its javadocs here.

More approrpiately what you could do here is read the entire line just like what you are doing here and then split the line based on the space character. So you get all the tokens in the first line in an array. The name is the first element of the array, the next are scores. Here the scores in the array are treated as strings, which you could convert into int or double as you require when you need to do the math on them. Then you could move on to read the next line and so on.

Use the split method of the String class to do this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.