Search code examples
javaaverageread-write

Java: issue calculating average from txt file


Hello everybody first post on here! i'm currently having some issues with my readfromfile() to calculate an average my issue is that its printing the ten numbers "stuck together" like 12345678910 i dont understand how i can calculate an average like this i tried token/10 and it returns 0000000000

any suggestions getting an average from this mess?

i tried returning token with %n%s which looks better but still when i divide by 10 it doesnt give me a correct number what am i doing wrong

package average;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Formatter;
import java.util.InputMismatchException;
import java.util.Scanner;

public class average {

    private static Formatter output;
    private static Scanner input;

    public static void main(String[] args) {

        openFileWrite();
        writeToFile();
        closeFile();
        openFileRead();
        readFromFile();
        closeFileRead();
    }

    public static void openFileRead() {      // gets file for "read"
        try {
            input = new Scanner(Paths.get("Numbers.txt"));
        } catch (IOException e) {
            System.out.println("Unable to read file");
        }
    }

    public static void openFileWrite() {     // gets file for "write"
        try {
            output = new Formatter("Numbers.txt");
        } catch (FileNotFoundException e) {
            System.out.println("Unable to open file");
        }

    }

    public static void readFromFile() {

        while (input.hasNextInt()) {

            int token = input.nextInt();

            System.out.print(token);

        }
    }

    public static void writeToFile() {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter 10 numbers");
        try {
            for (int i = 0; i < 10; i++) {

                System.out.println("Another Number Please");
                int total = input.nextInt();
                output.format("%s%n", total);
            }
        } catch (InputMismatchException e) {
            System.out.println("Please do not enter any letters");
            writeToFile();

        }
    }

    //required to close file for write
    public static void closeFile() {
        output.close();
    }

    //required to close file for read
    public static void closeFileRead() {
        input.close();
    }
}

Solution

  • Just change your readFromFile method as:-

    public static void readFromFile() {
            double average = 0;
            while (input.hasNextInt()) {
                int token = input.nextInt();
                average+=token;
            }
            System.out.println("Average ="+average/10);
    }