我是 java 编程新手,正在使用 NetBeans IDE 8.0,我正在尝试编写一个代码,该代码循环遍历充满数字的 txt 文件 (numbers.txt),查找 10 以下的所有数字以及所有数字超过 30,然后计算这些数字的平均值,并输出类似“范围内数字的平均值为 __”的内容
这是我到目前为止得到的代码,因为我不太确定哪里出了问题:
public class RangeAverage {
int average=0,num;
Scanner scan=new Scanner(new File("numbers.txt"));
while(scan.hasNextInt())
{
if((num=scan.nextInt()<10 || num >30)
{
average+=num;
}
}
System.out.println(" Average of numbers in range is "+average);
}
我得到的错误是这样的:
Scanner scan=new Scanner(new File("numbers.txt")); (Lightbulb symbol)
-cannot find symbol
symbol: class Scanner
location: class RangeAverage
-cannot find symbol
symbol: class Scanner
location: class RangeAverage
-cannot find symbol
symbol: class Scanner
location: class RangeAverage
-----------
上线
System.out.println(" Average of numbers in range is "+average); (a ! error)
-cannot find symbol
symbol: class out
location: class System
<identifier> expected
illegal start of type
-------------
如有任何帮助,我们将不胜感激,谢谢!
最佳答案
你不能把这些代码放在类区域中。使用方法。你可以在外面声明变量,但过程应该在方法内部发生。并且类应该有一个主要方法来运行。并且你正在计算总和而不是平均值需要将总和除以循环时间以获得平均值。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class RangeAverage{
public static void main(String[] args) throws FileNotFoundException {
int average = 0, num = 0, i=0;
Scanner scan = new Scanner(new File("numbers.txt"));
while (scan.hasNextInt()) {
if (((num = scan.nextInt()) < 10 || num > 30)){
average += num;
i++;
}
}
System.out.println(" Average of numbers in range is " + (average/i));
}
}
根据您的评论错误,该目录中没有这样命名的文本文件。因此将文件添加到目录或给出文本文件的完整路径。您需要转义斜杠 \
例子
如果你的文件路径是
C:\Users\Madhawa.se\Desktop\numbers.txt
那么路径应该是,
Scanner scan = new Scanner(new File("C:\\Users\\Madhawa.se\\Desktop\\numbers.txt"));
关于java - 循环遍历 txt 文件,查找某个范围内的数字及其平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26803484/