package 网络213; public class A3 { import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { // 随机生成100个整数 Random random = new Random(); List<Integer> nums = new ArrayList<>(); for (int i = 0; i < 100; i++) { nums.add(random.nextInt(100) + 1); } // 将数据写入num.txt文件 try (PrintWriter writer = new PrintWriter(new FileWriter("num.txt"))) { for (int i = 0; i < nums.size(); i++) { writer.print(nums.get(i)); if (i != nums.size() - 1) { writer.print(" "); } } } catch (IOException e) { e.printStackTrace(); } // 从文件中读出数据并显示 try (Scanner scanner = new Scanner(new File("num.txt"))) { List<Integer> readNums = new ArrayList<>(); while (scanner.hasNextInt()) { readNums.add(scanner.nextInt()); } System.out.println(readNums); } catch (FileNotFoundException e) { e.printStackTrace(); } } } } }
时间: 2024-02-14 21:07:26 浏览: 59
感谢您提供Java代码,但是代码中有一个多余的`}`,请删除该代码段的最后一个`}`即可。
以下是修改后的Java代码:
```java
import java.io.*;
import java.util.*;
public class A3 {
public static void main(String[] args) {
// 随机生成100个整数
Random random = new Random();
List<Integer> nums = new ArrayList<>();
for (int i = 0; i < 100; i++) {
nums.add(random.nextInt(100) + 1);
}
// 将数据写入num.txt文件
try (PrintWriter writer = new PrintWriter(new FileWriter("num.txt"))) {
for (int i = 0; i < nums.size(); i++) {
writer.print(nums.get(i));
if (i != nums.size() - 1) {
writer.print(" ");
}
}
} catch (IOException e) {
e.printStackTrace();
}
// 从文件中读出数据并显示
try (Scanner scanner = new Scanner(new File("num.txt"))) {
List<Integer> readNums = new ArrayList<>();
while (scanner.hasNextInt()) {
readNums.add(scanner.nextInt());
}
System.out.println(readNums);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
```
此代码的运行结果与之前提供的代码的运行结果相同,可以正确地随机生成100个整数并将它们写入`num.txt`文件中,并从文件中读取数据并显示。
阅读全文