用java来写 班里有60个同学,学号为“20208305X”,X为1-60。创建文件名为“D:\\ Test \学号. txt”的文件,内容为1-100的随机数。读取Test文件夹下的文件内容,输出到文件“D:\\ Test \score.txt”,内容为“学号:成绩”。
时间: 2024-05-06 19:21:16 浏览: 55
学生成绩.java
这是一个编程问题,我可以回答。请先下载Java开发环境,然后按照以下代码实现:
```java
import java.io.*;
import java.util.*;
public class RandomScoreGenerator {
public static void main(String[] args) {
String folderName = "D:\\Test";
File folder = new File(folderName);
if (!folder.exists()) {
folder.mkdirs();
}
for (int i = 1; i <= 60; i++) {
String fileName = folderName + "\\" + "20208305" + i + ".txt";
File file = new File(fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Random random = new Random();
try {
PrintWriter writer = new PrintWriter(file);
for (int j = 1; j <= 100; j++) {
int score = random.nextInt(100) + 1;
writer.println(score);
}
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
String scoreFileName = folderName + "\\" + "score.txt";
File scoreFile = new File(scoreFileName);
if (!scoreFile.exists()) {
try {
scoreFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
PrintWriter writer = new PrintWriter(scoreFile);
for (int i = 1; i <= 60; i++) {
String fileName = folderName + "\\" + "20208305" + i + ".txt";
File file = new File(fileName);
Scanner scanner = new Scanner(file);
int sum = 0;
while (scanner.hasNextInt()) {
sum += scanner.nextInt();
}
int average = sum / 100;
String line = "20208305" + i + ": " + average;
writer.println(line);
scanner.close();
}
writer.close();
System.out.println("Successfully generated random scores and output to file " + scoreFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
```
这段代码可以生成班里60个同学的1-100的随机数,并且存储在D:\Test文件夹下名为“20208305X.txt”的文件中。接着,从这些文件中读取成绩并生成“学号:成绩”格式的字符串,保存在D:\Test文件夹下名为“score.txt”的文件中。
阅读全文