使用java编写一个程序,从文件中读取一组整数,并将它们存储在数组中。然后计算数组的平均值、最大值和最小值
时间: 2024-03-06 20:49:06 浏览: 43
好的,我可以为您提供一个简单的代码示例,实现您的需求。请参考以下代码:
```java
import java.io.*;
import java.util.*;
public class ArrayCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入文件名:");
String filename = sc.nextLine();
int[] arr = readFile(filename);
if (arr != null) {
double avg = calculateAverage(arr);
int max = calculateMax(arr);
int min = calculateMin(arr);
System.out.println("平均值:" + avg);
System.out.println("最大值:" + max);
System.out.println("最小值:" + min);
}
}
// 从文件中读取一组整数并存储在数组中
public static int[] readFile(String filename) {
try {
Scanner fileScanner = new Scanner(new File(filename));
int count = fileScanner.nextInt();
int[] arr = new int[count];
for (int i = 0; i < count; i++) {
arr[i] = fileScanner.nextInt();
}
return arr;
} catch (IOException e) {
System.out.println("文件读取错误:" + e.getMessage());
return null;
}
}
// 计算数组的平均值
public static double calculateAverage(int[] arr) {
double sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
// 计算数组的最大值
public static int calculateMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
// 计算数组的最小值
public static int calculateMin(int[] arr) {
int min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
}
```
您需要在当前目录下创建一个名为 `input.txt` 的文件,文件的第一行是整数的个数,接下来的每一行是一个整数。例如:
```
5
1
2
3
4
5
```
然后您可以运行上面的代码,输入 `input.txt`,程序会输出整个数组的平均值、最大值和最小值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)