인쇄하는 방법의 결과로 공허 유형은 방법으로 파일은 Java PrintWriter

0

질문

나는 운동을 하 고 있는 활동을 위한 Java 프로그래밍은 물론,이 질문으로 그렇:

쓰기 방식이라는 printTree 출력하는 파일에 삼각형의 별표에 따라 높이 값을 전달하는 절차이다. 이 테스트 방식에 주요 방법입니다.

  • E.g. 삼각형의 높이 3 해야 라는 파일에 출력을 file14:

난 그냥 확인을 작성하는 방법을 반환하는 파일에서 주요 방법입니다. 고 싶을 최소화를 가져오는 다른 java.io 방법을 고객께서는 FileWriter,하지만 어떤 도움을 평가,감사합니다.

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();
        }
    } 
}
call file java methods
2021-11-24 02:22:55
2

최고의 응답

3

네 관찰. System.outPrintStream (고 전달할 수 PrintStream 당신의 방법). try-with-Resources 할 수 있을 제거하는 명시적 close() 호출합니다. 용 System.getProperty("user.home") 를 작성할 수 있습으로 홈 폴더로 직접(이는 유용 할 수 있습니다). 고 사용 j < iif (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();
    }
}

또한,이후 자바 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)
    }
}
2021-11-24 02:40:07

더 나은 대답--감사
Hovercraft Full Of Eels

내가 너무 잘 보내는 개체에서 인수로 사용하는 방법,그러나 나는 가정과 유사한 다른 응답,이것은 기본적으로 그렇게 그것의 모든"하나 늘어선":을 선언하는 파일의 이름을 지정. 다에 있는 그것을 인쇄 스트림을 그렇게 그 sendable 인수로? 여러분의 의견을 듣고 싶은 일부 선명도 포인트,나의 코스가 f 초기 단계에서의 작성하는 파일 그래서 나는 더 이해
Achor Gabriel

System.outPrintStream. 을 구성할 수 있습니다 당신의 자신 PrintStream 인스턴스가 있습니다. 쓰 File. 이와 함께 생성자. 으로 보내는 개체를 인수로, main(String[] args) (이것은 아주 당신이 먼저). 는 희망 도움이 됩니다.
Elliott Frisch

@ElliottFrisch 감사합니다! 나는 생각이 끝날 것이 필요한 더 많은 연구에서 끝나지만,나는 생각할 것도에서 오른쪽 방향입니다. 당신을 감사하는 헤더에 사실은,내가 알지 못했지만,이제는 않습니다. 많이 감사
Achor Gabriel
-2

당신은 그것을 해결할 수 있 다음과 같이

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");
        }
    } 
}
2021-11-24 02:35:23

감사는 크게 당신의 대답이다! 내 생각에 나는 길이 비록 죄송,하지 않는 것으로 알고 정말과 함께 작동하는 방법 PW 매개 변수로 나중에 참조할 수 있습니다. 당신을 감사하지만,많이 감사합니다.
Achor Gabriel

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................