IO练习:随机生成1000个[50,1000)的整数,按照每行10的方式,输出 到文件中,并依次读出文件中每行的首个数字累计求和并输出 java代码
时间: 2024-03-11 11:51:20 浏览: 48
生成随机数的Java代码如下:
```java
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class RandomNumberGenerator {
public static void main(String[] args) {
Random random = new Random();
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter("random_numbers.txt");
for (int i = 0; i < 1000; i++) {
int randomNumber = random.nextInt(950) + 50; // 生成50到999之间的随机数
fileWriter.write(randomNumber + " ");
if ((i + 1) % 10 == 0) { // 每10个数字换一行
fileWriter.write("\n");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
读取文件中每行的首个数字并累加求和的Java代码如下:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class RandomNumberSum {
public static void main(String[] args) {
FileReader fileReader = null;
BufferedReader bufferedReader = null;
int sum = 0;
try {
fileReader = new FileReader("random_numbers.txt");
bufferedReader = new BufferedReader(fileReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
String[] numbers = line.split(" ");
sum += Integer.parseInt(numbers[0]);
}
System.out.println("每行首个数字累计求和为:" + sum);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
阅读全文