Java简单代码把杨辉三角写入文档中在从文档中打印出来
时间: 2023-06-13 19:07:56 浏览: 106
以下是Java代码实现:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class YangHuiTriangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入杨辉三角的行数:");
int n = scanner.nextInt();
scanner.close();
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];
}
}
File file = new File("yanghui.txt");
try {
FileWriter writer = new FileWriter(file);
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
writer.write(triangle[i][j] + " ");
}
writer.write("\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
Scanner fileScanner = new Scanner(file);
while (fileScanner.hasNextLine()) {
System.out.println(fileScanner.nextLine());
}
fileScanner.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该程序先从控制台读取杨辉三角的行数,然后使用二维数组存储杨辉三角,并将其写入文本文件中。最后,程序使用Scanner从文本文件中读取杨辉三角并打印到控制台。
阅读全文