Hey guys. I need help with a program I'm trying to write. I need to read scores from an ASCII file and display them. I also need to display an error message for any score that falls outside of the range of 0 to 100. And after doing that, I need to display an average of all of the VALID scores (scores from 0 to 100).

Here's my code so far:

import java.util.Scanner;
import java.io.*;

public class ReadAndAverageScores  {
   public static void main (String[] args)throws FileNotFoundException {
     
   System.out.println("This program reads text from a file named 'TestScores.dat'.");
   
   File anyFile = new File("TestScores.dat");

   Scanner inputStream = new Scanner(anyFile);
   
   System.out.println("-Contents of file "+anyFile+"-");
   
 int lineNum=1;
 
 while (inputStream.hasNextInt()){
   
 System.out.println("Line "+lineNum+": "+inputStream.nextInt());
  lineNum++;
  
 }
   }
}

I know how to read the scores, just not display the error message for the scores out side of the range and average the ones inside of the range.

Any help would be greatly appreciated!

First, you need the score to be in a variable, so that you can work with it. So I'd start by making this change:

int testScore = inputStream.nextInt();
			System.out.println("Line " + lineNum + ": " + testScore);

Then you'll need if statement(s) to determine if the scores are valid. For the valid scores, you'll need to accumulate their values into a sum, and also count them. After you've read all of them, divide the sum by the count to get the average. The average might not be an exact integer value, so you might want to consider using a different data type, like 'double' at some point.

Displaying an error message is easy; like this:

System.out.println("Here's an error message for ya!");

When I do that the loop keeps going. If I delete the loop, it only reads one line.

One way to get out of a loop is to use the 'break;' statement.

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.