io输入输出流那章java把杨辉三角写进去读取并打印出来
时间: 2024-03-01 11:51:09 浏览: 44
好的,我可以帮你解决这个问题。下面是一个简单的 Java 程序,可以从控制台读取输入行数 n,然后将杨辉三角的前 n 行写入到文件中,并读取并打印出来:
```java
import java.io.*;
public class YanghuiTriangle {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入行数 n:");
int n = 0;
try {
n = Integer.parseInt(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
String fileName = "yanghui_triangle.txt";
try (PrintWriter writer = new PrintWriter(new FileWriter(fileName))) {
int[][] triangle = new int[n][n];
for (int i = 0; i < n; i++) {
triangle[i][0] = 1;
triangle[i][i] = 1;
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
writer.print(triangle[i][j] + " ");
}
writer.println();
}
System.out.println("杨辉三角已写入文件 " + fileName);
} catch (IOException e) {
e.printStackTrace();
}
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
System.out.println("读取的杨辉三角如下:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个程序中,我们首先通过 BufferedReader 从控制台读取输入行数 n,然后使用 PrintWriter 将前 n 行杨辉三角写入到文件 yanghui_triangle.txt 中。最后,我们使用 BufferedReader 再次读取文件并打印输出。注意,在 try-with-resources 语句中创建的流会自动关闭。
阅读全文