大家好,第一個(gè)帖子在這里!我目前有一些問題與我的readfromfile()計(jì)算平均值我的問題是它打印十個(gè)數(shù)字“粘在一起”像12345678910我不明白我如何計(jì)算這樣的平均值,我嘗試了token / 10,它返回0000000000任何建議從這個(gè)混亂中獲得平均值?我嘗試返回帶有%n%s的令牌,這看起來更好,但是當(dāng)我除以10時(shí),它仍然沒有給我一個(gè)正確的數(shù)字,我做錯(cuò)了什么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(); } }
1 回答

眼眸繁星
TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
只需將你的 readFromFile 方法更改為:-
public static void readFromFile() {
double average = 0;
while (input.hasNextInt()) {
int token = input.nextInt();
average+=token;
}
System.out.println("Average ="+average/10);
}
添加回答
舉報(bào)
0/150
提交
取消