我正在為我的 Java 編程課程做練習,問題是這樣的:
撰寫一個名為 printTree 的方法,該方法根據傳遞給程序的高度值將星號三角形輸出到檔案中。在 main 方法中測驗這個方法。
- 例如,高度為 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();
}
}
}
uj5u.com熱心網友回復:
四觀察。System.out是 a PrintStream(并且您可以將 a 傳遞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)
}
}
uj5u.com熱心網友回復:
你可以這樣解決
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 = "\r\n";
}
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("\r\n");
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367718.html
上一篇:保存一個b-tree檔案以供稍后使用python讀取
下一篇:fork()開始執行
