简体   繁体   中英

java printing pattern to a file using PrintWriter

I am writing a JAVA program to print a Diamond pattern to a file. The pattern is correctly printed on the console but its getting printed properly to the file. Here is the code:

            static void print_row(int cnt,PrintWriter output)
            {
                 while(cnt --> 0) 
                     System.out.print("* "); 
                     output.print("* "); // or for loop, I just think --> is cute
                     output.println();
                     System.out.println();
            }

            static void diamond(int maxrow, int row,PrintWriter output)
            {
                 if (row >= maxrow)
                 {
                     print_row(row,output);
                 }
                 else
                 {
                     char[] chart = new char[maxrow-row];
                     Arrays.fill(chart,' ');
                     String t = new String(chart);

                     System.out.print(t);
                     output.print(t);
                     print_row(row,output);

                     diamond(maxrow, row+2,output);
                     char[] chard = new char[maxrow-row];
                     Arrays.fill(chard,' ');
                     String d = new String(chard);
                     output.print(d);
                     System.out.print(d);
                     print_row(row,output);
                 }
            }

the output is like this

                * 
              * 
            * 
          * 
        * 
          * 
            * 
              * 
                * 

The while loop in print_row only loops over System.out.println . To get the same output on the terminal in the the PrintWriter , you should include it in the loop too:

static void print_row(int cnt, PrintWriter output)
{
    while(cnt --> 0) {
        System.out.print("* ");
        output.print("* "); // Here!
    }
    output.println();
    System.out.println();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM