我最近刚刚开始学习 Java,正在做练习。
我正在尝试读取文本文件并显示最大值、最小值和平均值。到目前为止,我能够输出平均值,但在尝试找到最大值时遇到了问题。我计划将最小值设置为最大值+1,但我似乎对最大值有疑问。代码如下,错误输出如下。谁能告诉我哪里错了?
谢谢!
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
String fileName= "scratch.txt";
Scanner inputStream=null;
try
{
inputStream = new Scanner (new File (fileName));
}
catch (FileNotFoundException exception)
{
System.out.println("The file: " +fileName +" has not been found, exiting program.");
System.exit(0);
}
int sum=0;
int i=0;
int max=0;
int min=0;
while (inputStream.hasNextInt())
{
if(inputStream.nextInt()>max)
{
max=inputStream.nextInt();
}
sum=+inputStream.nextInt();
i++;
}
System.out.println(max);
System.out.println("The integer average is: " +sum/i);
inputStream.close();
}
}
错误输出:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:945)
at java.base/java.util.Scanner.next(Scanner.java:1602)
at java.base/java.util.Scanner.nextInt(Scanner.java:2267)
at java.base/java.util.Scanner.nextInt(Scanner.java:2221)
at Main.main(Main.java:27)