请用JAVA语言按如下要求编写程序,放到一个代码里:IO练习:随机生成1000个[50,1000)的整数,按照每行10的方式,输出到文件中,并依次读出文件中每行的首个数字累计求和并输出。
时间: 2024-03-11 19:51:36 浏览: 31
以下是实现题目要求的JAVA代码,包含生成随机数和读取文件计算累加和的功能:
```java
import java.io.*;
import java.util.Random;
public class RandomNumberIO {
public static void main(String[] args) {
// 生成随机数并写入文件
writeRandomNumbersToFile();
// 依次读取文件中每行的首个数字并计算累加和
int sum = readFirstNumberAndSum();
// 输出累加和
System.out.println("The sum of the first numbers in each line is: " + sum);
}
/**
* 生成随机数并写入文件
*/
public static void writeRandomNumbersToFile() {
int count = 0;
Random random = new Random();
File file = new File("numbers.txt");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
for (int i = 0; i < 1000; i++) {
int number = random.nextInt(950) + 50;
writer.write(number + " ");
count++;
if (count % 10 == 0) {
writer.newLine();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 依次读取文件中每行的首个数字并计算累加和
*
* @return 累加和
*/
public static int readFirstNumberAndSum() {
int sum = 0;
File file = new File("numbers.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
String[] numbers = line.trim().split("\\s+");
sum += Integer.parseInt(numbers[0]);
}
} catch (IOException e) {
e.printStackTrace();
}
return sum;
}
}
```
运行以上代码,就可以实现题目要求的功能了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)