Java:从txt文件计算平均值的问题

大家好,第一个帖子在这里!我目前有一些问题与我的readfromfile()计算平均值我的问题是它打印十个数字“粘在一起”像12345678910我不明白我如何计算这样的平均值,我尝试了token / 10,它返回0000000000


任何建议从这个混乱中获得平均值?


我尝试返回带有%n%s的令牌,这看起来更好,但是当我除以10时,它仍然没有给我一个正确的数字,我做错了什么


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();


        }

    }


慕丝7291255
浏览 99回答 1
1回答

眼眸繁星

只需将你的 readFromFile 方法更改为:-public static void readFromFile() {&nbsp; &nbsp; &nbsp; &nbsp; double average = 0;&nbsp; &nbsp; &nbsp; &nbsp; while (input.hasNextInt()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int token = input.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; average+=token;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Average ="+average/10);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java