-2

I was tasked with reading a data.txt file using the scanner import. The data.txt file looks like this:

1 2 3 4 5 6 7 8 9 Q

I need to read and find the average of these numbers, but stop when I get to something that is not an integer.

This is the code that I have so far.

public static double fileAverage(String filename) throws FileNotFoundException {
    Scanner input = new Scanner(System.in);
    String i = input.nextLine();
    while (i.hasNext);
    return fileAverage(i); // dummy return value. You must return the average here.
} // end of method fileAverage

As you can see I did not get very far and I cannot figure this out. Thank you for your help.

AbdelAziz AbdelLatef
  • 3,650
  • 6
  • 24
  • 52
juicecup
  • 1
  • 2

1 Answers1

1

First, your Scanner should be over the file filename (not System.in). Second, you should be using Scanner.hasNextInt() and Scanner.nextInt() (not Scanner.hasNext() and Scanner.nextLine()). Finally, you should add each int you read to a running total and keep track of the count of numbers read. And, I would use a try-with-resources statement to ensure the Scanner is closed. Something like,

public static double fileAverage(String filename) throws FileNotFoundException {
    try (Scanner input = new Scanner(new File(filename))) {
        int total = 0, count = 0;
        while (input.hasNextInt()) {
            total += input.nextInt();
            count++;
        }
        if (count < 1) {
            return 0;
        }
        return total / (double) count;
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • how would I call this method then? im not able to call fileAverage(filename); anywhere after that because it says the code is unreachable or it says the return type is missing? – juicecup Nov 20 '19 at 01:07
  • `fileAverage(filename);` - works fine here. How are you calling it? Which error is it? What version of Java are you targeting? – Elliott Frisch Nov 20 '19 at 01:11
  • I am using javaSE-12 and am placing it after defining the method. i am getting errors that say code cannot be reached, return type is missing for the method, and something that says syntax error insert variabledeclaratorID. – juicecup Nov 20 '19 at 01:21
  • Because you can't call a method without being in a block (usually in `main`). – Elliott Frisch Nov 20 '19 at 01:35
  • Right. Okay i found my issue and got it all to work. Greatly appreciate your help! – juicecup Nov 20 '19 at 01:41