Cómo imprimir el resultado de un tipo void método en un archivo con Java PrintWriter

0

Pregunta

Estoy haciendo ejercicio para mi curso de programación Java, la pregunta va así:

Escribir un método llamado printTree que los resultados a un archivo de un triángulo de asteriscos basado en el valor de la altura que pasan al procedimiento. Prueba este método en el método main.

  • E. g. Triángulo de altura de 3 debe salida a un archivo llamado file14:

No estoy seguro de cómo escribir el retorno void para el archivo que me he hecho en el método main. Me gustaría minimizar la importación de cualquier otro java.io métodos aparte de FileWriter, pero cualquier ayuda es muy apreciada, Gracias.

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

Mejor respuesta

3

Cuatro observaciones. System.out es un PrintStream (y se podría pasar una PrintStream a su método). try-with-Resources le permite eliminar explícito close() las llamadas. El uso de System.getProperty("user.home") permite escribir en la carpeta de inicio directamente (que puede ser útil). Y el uso de j < i en lugar de if (j < i) en su bucle interno. Como,

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();
    }
}

También, desde 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)
    }
}
2021-11-24 02:40:07

La mejor respuesta ... gracias
Hovercraft Full Of Eels

No estoy muy versado con el envío de un objeto como argumento a los métodos, pero estoy asumiendo similar a la otra respuesta, básicamente, esto hace que sea así que todos sus "uno-forrado": declarar el archivo, nombres de. y en un flujo de impresión hace por lo que su sendable como un argumento? Me encantaría saber algo más de claridad de los puntos, Mi curso es de f en las primeras etapas de escribir en el archivo así que me gustaría entender más
Achor Gabriel

System.out es un PrintStream. Usted puede construir su propio PrintStream las instancias. Para escribir en un File. Con este constructor. Como para el envío de un objeto como argumento, main(String[] args) (es la primera cosa que hacer). Espero que ayude.
Elliott Frisch

@ElliottFrisch Gracias! Creo que esto va a terminar y que requieren más trabajo de investigación en mi final, pero, creo que voy a ser guiado en la dirección correcta. Gracias por la principal encabezado de hecho, algo que yo no sabía, pero ahora lo hago. Muy apreciado
Achor Gabriel
-2

Usted podría solucionarlo como este

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;
    } 
}

Esto es un poco fea manera de resolverlo rápidamente.

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

Agradezco mucho su respuesta! Creo que me voy a apartarme de esto, sin embargo, lo siento, como yo no sé realmente cómo trabajar con el MP, como un parámetro de referencia para el futuro. Gracias a usted, sin embargo, muy apreciado.
Achor Gabriel

En otros idiomas

Esta página está en otros idiomas

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