jQuery in Action, 2nd edition
The moose likes Java in General and the fly likes Read in file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Read in file" Watch "Read in file" New topic

Read in file

Michelle Parker

Joined: Apr 23, 2008
Posts: 5

I have issues with this program:

package Scores;

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

public class Scores {
public static void main(String[] args) throws Exception {
int total=0;
int count=0;
// Create a File instance
java.io.File file = new java.io.File("Scores.txt");

// Create a Scanner for the file
java.util.Scanner input = new java.util.Scanner(file);

// Read data from a file
while (input.hasNext()) {
int score = input.nextInt();
total = total + score;
average = total / count;
System.out.println("The total = " +total +"\n"
+ "The average = " +average);

// Close the file

With the Scores.txt containing the following:

55 88 99 50 66 31 45 15 48

Mucho Gracias!
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
What are these issues ? Does it not compile - post the exact error messages - or does it not do what you want - tell us what it is doing and what you want it to do.

Michelle Parker

Joined: Apr 23, 2008
Posts: 5
Hi Joanne,

It doesn't compile at all. No error messages.
Michelle Parker

Joined: Apr 23, 2008
Posts: 5
I need it to read in the scores from Score.txt
then give the average of them.
Rob Spoor

Joined: Oct 27, 2005
Posts: 19911

No error messages? Really? Because I get some error messages that clearly specify the problem:

Where do you declare variable average?

How To Ask Questions How To Answer Questions
Guido Sautter
Ranch Hand

Joined: Dec 22, 2004
Posts: 142
The problem is in the line " average = total / count;". The variable "average" has not been declared. Change that very line to "int average = total / count;", then it will compile without problems.

Maybe you might give a try to using an IDE like Eclipse, this will help you a lot in preventing such errors.
I agree. Here's the link: http://aspose.com/file-tools
subject: Read in file