gpt4 book ai didi

Java 输入文件无法打印

转载 作者:行者123 更新时间:2023-12-02 07:14:18 25 4
gpt4 key购买 nike

我正在做一项作业,需要从 java 中的输入文件中打印 3 组不同分数的平均值。平均值必须四舍五入到小数点后两位。我尝试创建扫描仪,以便可以添加输入文件中的小数并求平均值,但是当我单击运行时,netbeans 只是运行并且没有打印任何内容。我也没有收到错误。任何关于如何让它运行的提示将不胜感激。

输入文件内容:7.88 6.44 5.66 3.447.50 9.80 4.33 2.318.99 7.62 3.67 4.39

``这是代码(所有必需的导入都已导入)

public static void main(String[] args) throws IOException {

{
Scanner sc = new Scanner(new File("Gym.in"));

double Number = sc.nextFloat();
{
NumberFormat fmt = NumberFormat.getNumberInstance();
fmt.setMinimumFractionDigits(2);
fmt.setMaximumFractionDigits(2);

Scanner sf = new Scanner(new File("Gym.in"));
int maxIndx = -1;
String text[] = new String[100];
while (sf.hasNext())
;
{
maxIndx++;
text[maxIndx] = sf.nextLine();
System.out.println(text[maxIndx]);
}
sf.close();

String answer;
double sum;
double average;

for (int j = 0; j <= maxIndx; j++) {
StringTokenizer st = new StringTokenizer(text[j]);
Scanner sg = new Scanner(text[j]);
System.out.println(text[j]);

Scanner ss = new Scanner(text[j]);
sum = 0;
average = sum / 10;
answer = "For Competitor #1, the average is: ";

while (sc.hasNext()) {
double i = sc.nextDouble();
answer = answer + i;
sum = sum + i;
}

answer = answer + average;
System.out.println(answer);

}
}
}
}

最佳答案

此代码有几个问题 - 一个是您期望 '.' 作为小数点字符,但在我的语言环境中它是 ',',所以我得到的第一件事是 java.util.InputMismatchException

无论如何,您的代码似乎没有执行任何操作的原因是以下几行:

 while (sf.hasNext())
;

这实际上是一个无限循环。当您的扫描仪有更多 token 要传送时,您正在循环,但您永远不会检索下一个 token 。因此 hasNext() 将永远返回 true

如果删除 ; 那么您的代码就会运行。不过我还没有验证结果。

<小时/>

您还需要重新计算平均值:使用您的代码,您的平均值将始终保持 0.0:

sum = 0;
average = sum / 10;
...
answer = answer + average;
System.out.println(answer);

我也不确定为什么你想将总和除以 10 - 在你的情况下这可能应该是 12(假设“每组分数”是输入文件中的一行)。总而言之,您的方法还不错 - 您基本上必须删除一些不必要的代码并将第二个循环中的语句按正确的顺序放置:)

for (int j = 0; j <= maxIndx; j++) {
double sum = 0;
double average = 0;

Scanner ss = new Scanner(text[j]);
String answer = "For Competitor #1, the average is: ";

while (sc.hasNext()) {
double i = sc.nextDouble();
sum = sum + i;
}
average = sum / 12; // better use number of tokens read instead of hard coded 12

answer = answer + average;
System.out.println(answer);
}

最后,您不需要将每一行读入 String 数组 - 只需读取一行并立即处理它。当文件中的行数超过 100 行时,这可以节省内存并避免 IndexOutOfBoundsException。我把这个留给你作为练习:)

关于Java 输入文件无法打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15130527/

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