gpt4 book ai didi

java - 无法弄清楚如何读取txt文件中的分数并输出到Java中的不同txt文件

转载 作者:行者123 更新时间:2023-11-30 03:32:15 25 4
gpt4 key购买 nike

我正在学习编程基础 1,我的教授要求我们创建一个包含 10 个分数的 txt 文件,创建一个程序来读取分数,将它们相加,求和,求平均值,最后导出结果到不同的txt文件。

到目前为止,我已经了解了如何创建和写入文件,但读取 txt 文件中的分数却变得越来越困难。它可以编译,但会不断读出每当运行时都必须发生的异常。

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

public class FahrDylanFileInputOutput {
public static void main(String[] args) throws IOException {
double sum = 0.0;
File input = new File("dylfahrinput.txt");
Scanner inputFile = new Scanner(input);
while (inputFile.hasNext()) {
String line = inputFile.nextLine();
double fraction = Double.parseDouble(line);
sum = sum + fraction;
}
double avg = sum / 10;

inputFile.close();

PrintWriter pw = new PrintWriter("dylfahroutput.txt");
pw.println("Sum is : " + sum + "\n Average is: " + avg);
// add this to the end of the overall program.
pw.close();

System.out.println("Data has been written to the txt file.");
}
}

我可能做错了什么?分数为 1/10 - 9/10

更新:现在是完整的代码,仍然相同的命令提示消息:

public static void main(String[] args) throws IOException {
double numsum = 0.0;
double densum = 0.0;
File input = new File("dylfahrinput.txt");
Scanner inputFile = new Scanner(input);

while (inputFile.hasNext()) {
String line = inputFile.nextLine();
String[] fract = line.split("/");
int num = Integer.valueOf(fract[0]);
int den = Integer.valueOf(fract[1]);
double fraction = num / den;
numsum = (numsum + num);
densum = den;
}
double avg = numsum / 10;
inputFile.close();

PrintWriter pw = new PrintWriter("dylfahroutput.txt");
pw.println("Sum is : " + numsum + "/" + densum + "\n Average is: " + avg);
// add this to the end of the overall program.
pw.close();

System.out.println("Data has been written to the txt file.");
}

最佳答案

首先,看起来您基本上走在正确的轨道上,至少在读取文件、使用变量存储您已读取的分数之和等方面是如此。

大概line将包含类似 "1/10" 的字符串值或"6/10"当您遍历文件的各行时。

我建议查看 Double.parseDouble(String) 的文档,因为它需要一个十进制格式的数字。

因此,您必须自己解析该字符串。你会怎么做?

您有两个由“/”字符分隔的整数。如何单独获取整数?

 

尝试 String.split()

 

new String("I love pizza").split(" ")会给你[“我”,“爱”,“披萨”]。
new String("243/19").split("/")会给你 ["243","19"]。

现在,假设您有几个整数,分别代表分子和分母。对于如何处理它们,您有多种选择。

最简单的方法是将分子相加并忽略分母。

关于java - 无法弄清楚如何读取txt文件中的分数并输出到Java中的不同txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28749170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com