查找文本文件中某些数字的平均值

时间:2017-10-24 23:27:00

标签: java text-files average

这是我的代码:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
 public class QuestionTwo
{

public static void main(String[] args) throws FileNotFoundException 
{
 System.out.println("Please enter a file name");
Scanner keyboard = new Scanner(System.in);

double average;
double numbertocheck;
int length;

String filename = keyboard.next();
Scanner reader = new Scanner (new File(filename));

length = reader.nextInt();

//Here is where I would put the statement that says "File is not found, enter the filename again"

System.out.println("The number to check: ");

numbertocheck = keyboard.nextDouble();

if (length > numbertocheck)
{
  //here is where I would put the average calculation

  System.out.println("The average of the numbers that are greater than" + numbertocheck + "is " /**+ average*/);

}

}
}

文本文件如下:

30
44
23
56
43
2
32
35
90
12

我的输出一无所获;它简单地问了两个问题并画了一个空白(甚至在我把一堆东西写成评论之前)。此代码试图回答这个问题:

"编写一个程序,要求用户输入包含一组整数值的文件名,然后要求用户输入整数。

程序应显示数字的平均值 大于输入数字。使用记事本或其他文本编辑器创建一个可用于测试程序的简单文件。

首先,用户输入文件名如下: 输入文件名:input.txt 例如,如果文件'input.txt'包含以下数字:

30
44
23
56
43
2
32
35
90
12

然后,如果用户输入整数,则为:

The number to check: 40

程序应将输出显示为:

The average of the numbers that are greater than 40 is 58.25

请注意,数字44,56,43和90的平均值为233/4 = 58.25。平均值必须显示最多两位小数。

如果未找到输入文件,则必须提示用户再次输入文件名,并显示以下消息

“File is not found, enter the filename again”.

然后会再次提示问题,直到找到有效的文件。"

在解析文本文件并找到大于所要求值的数字的平均值时,问题出现了。然后循环问题,要求用户输入文件名,然后重复该问题,直到找到文件。我曾想过使用Decimal格式类,但不知道如何正确使用它。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

我的第一个评论是你可能想要上一些课。这是非常基本的东西。

但要回答你的问题,请使用while循环,其中包含if / else语句,以获得正确的输入。

对于下一个问题,您可能希望使用.nextLine而不是.next,因为某些文件名中包含空格。

第三个问题,使用for循环一次检查一个整数,并将其与所需范围进行比较。然后使用if / if else语句/ switch语句和一个数组来存储值,并在检查完所有值之后,对数组的内容进行数学运算。

同样,我强烈建议您参加一些基础的Java课程。

相关问题