【问题标题】:java printing pattern to a file using PrintWriterjava使用PrintWriter将模式打印到文件
【发布时间】:2017-11-05 18:13:52
【问题描述】:

我正在编写一个 JAVA 程序来将菱形图案打印到文件中。该模式已正确打印在控制台上,但已正确打印到文件中。代码如下:

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

输出是这样的

                * 
              * 
            * 
          * 
        * 
          * 
            * 
              * 
                * 

【问题讨论】:

  • 你的问题对我来说没有意义......文件中没有正确打印吗?

标签: java file design-patterns printwriter


【解决方案1】:

print_row 中的 while 循环仅在 System.out.println 上循环。要在PrintWriter 中的终端上获得相同的输出,您也应该将其包含在循环中:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多