filename = input("Enter the file name: ") try: with open(filename, "r") as file: scores = [int(score) for score in file.read().split()] total = sum(scores) average = total / len(scores) print("Total: ", total) print("Average: ", average) except FileNotFoundError: print("File not found.")用JAVA解答
时间: 2023-12-03 17:43:14 浏览: 63
以下是相应的 Java 代码:
```
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FileAverage {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = scanner.nextLine();
try {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int total = 0;
int count = 0;
while (fileScanner.hasNextInt()) {
int score = fileScanner.nextInt();
total += score;
count++;
}
if (count > 0) {
double average = (double) total / count;
System.out.println("Total: " + total);
System.out.println("Average: " + average);
} else {
System.out.println("No scores found in file.");
}
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
}
```
这个 Java 程序与 Python 版本非常相似。它也使用 `Scanner` 对象读取文件,并且在读取过程中计算分数的总和和数量。然后,它计算平均值并输出结果。如果文件不存在,则会捕获 `FileNotFoundException` 并输出错误消息。
阅读全文