我正在为我的Java编程课程做练习,问题是这样的:
编写一个名为printTree的方法,根据传递给过程的高度值向文件输出一个星号三角形。在主方法中测试此方法。
- 例如,高度为3的三角形应输出到名为file14的文件:
我只是不知道如何将void返回写入到我在main方法中创建的文件中。除了FileWriter之外,我想尽量减少任何其他java.io方法的导入,但我们非常感谢您的帮助,谢谢。
import java.io.PrintWriter;
public class OutputToFile14 {
public static void main(String[] args) throws Exception{
//Creating PrintWriter
PrintWriter output = new PrintWriter("file14.txt");
//writing method output to file
output.write(printTree(4));
//saving file
output.close();
}
public static void printTree (int height) throws IOException{
for (int i = 0; i < height; i++) {
for (int j = 0; j < height; j++) {
if (j < i) {
System.out.print("*");
}
}
System.out.println();
}
}
}
四个观察结果。System.out
是PrintStream
(您可以将PrintStream
传递给您的方法(。try-with-Resources
允许您消除显式close()
调用。使用System.getProperty("user.home")
可以直接写入主文件夹(这很方便(。并且在内部循环中使用j < i
而不是if (j < i)
。比如
public static void main(String[] args) throws Exception {
try (PrintStream output = new PrintStream(
new File(System.getProperty("user.home"), "file14.txt"))) {
printTree(output, 4);
}
}
public static void printTree(PrintStream out, int height) throws IOException {
for (int i = 0; i < height; i++) {
for (int j = 0; j < i; j++) {
out.print("*");
}
out.println();
}
}
此外,由于Java 11,
public static void printTree(PrintStream out, int height) throws IOException {
for (int i = 0; i < height; i++) {
out.println("*".repeat(i)); // You might want "*".repeat(1 + i)
}
}
你可以像这个一样解决它
import java.io.PrintWriter;
public class OutputToFile14 {
public static void main(String[] args) throws Exception{
//Creating PrintWriter
PrintWriter output = new PrintWriter("file14.txt");
//writing method output to file
output.write(printTree(4));
//saving file
output.close();
}
public static String printTree (int height) throws IOException{
String output = "";
for (int i = 0; i < height; i++) {
for (int j = 0; j < height; j++) {
if (j < i) {
System.out.print("*");
output += "*";
}
}
System.out.println();
output += "rn";
}
return output;
}
}
这是一种有点丑陋的快速解决方法。
import java.io.PrintWriter;
public class OutputToFile14 {
public static void main(String[] args) throws Exception{
//Creating PrintWriter
PrintWriter output = new PrintWriter("file14.txt");
//writing method output to file
//output.write(printTree(4));
printTree(4, output);
//saving file
output.close();
}
public static void printTree (int height, PrintWriter pw) throws IOException{
for (int i = 0; i < height; i++) {
for (int j = 0; j < height; j++) {
if (j < i) {
System.out.print("*");
pw.write("*");
}
}
System.out.println();
pw.write("rn");
}
}
}