无法让我的嵌套循环后PrintWritter正确打印到.txt

时间:2015-05-05 17:03:13

标签: java nested printf printwriter

我被要求使用PrintWriter将乘法问题的网格打印到.txt文件。一切都运作良好,但我遇到了一些严重的麻烦,让我的代码按照我的要求打印。我一直在使用printf左/右缩进。任何帮助将非常感激。

我没有意识到我的帐户不会上传图片,所以很抱歉这个混乱。我以为我发布了所需的输出。这就是它的外观。

基本上它是按10行创建3列数字。我可以让它工作,但没有列和行的分离。左边是奇数,右边是偶数。

1 * 1 = 1                 1 * 2 = 2
2 * 1 = 2                 2 * 2 = 4
3 * 1 = 3                 3 * 2 = 6
4 * 1 = 4                 4 * 2 = 8
ect
10 * 1 = 10              10 * 2 = 20



1 * 3 = 3
2 * 3 = 6
ext.....




import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;

public class LabPrintTimeTables {

public static void main(String[] args) throws IOException
{
        printTimeTable();

}

private static void printTimeTable() throws FileNotFoundException
{
    try {
        File file = new File ("Lab Print Time Table");

        PrintWriter printWriter = new PrintWriter("TimeTables.txt");

        printWriter.println ("\tTimes Tables:\n");
        for(int i = 0; i <= 10; i++)
        {
            for(int j = 1; j <= 10; j++ )
            {
                if (i % 10 == i) {
         System.out.printf("%-2d * %-2d = %-2d", j, i + i + 1, i   * j + 1);
         System.out.printf("%10d * %d = %d\n", j, i + i + 2, i * j + 1);
                }


            }

        }
        printWriter.close ();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
   }
}

1 个答案:

答案 0 :(得分:0)

您不是写信给printWriter,而只是写入控制台。在内部printWriter循环中写入for对象以将内容存储在文件中。等。

for(int j = 1; j <= 10; j++ )
            {
                if (i % 10 == i) {
         System.out.printf("%-2d * %-2d = %-2d", j, i + i + 1, i   * j + 1);
         System.out.printf("%10d * %d = %d\n", j, i + i + 2, i * j + 1);

         printWriter.printf("%-2d * %-2d = %-2d", j, i + i + 1, i
                            * j + 1);
         printWriter.printf("%10d * %d = %d\n", j, i + i + 2, i
                            * j + 1);
                }

修改

我希望您尝试获得所需的输出,但如果您仍然遇到问题,请转到此处。

private static void printTimeTable() throws FileNotFoundException {
    try {
        File file = new File("Lab Print Time Table");

        PrintWriter printWriter = new PrintWriter("TimeTables.txt");

        printWriter.println("\tTimes Tables:\n");
        for (int i = 1; i <= 10; i += 2) {
            for (int j = 1; j <= 10; j++) {

                System.out.printf("%-2d * %-2d = %-2d", j, i, i * j);
                System.out
                        .printf("%10d * %d = %d\n", j, i + 1, j * (i + 1));

                printWriter.printf("%-2d * %-2d = %-2d", j, i, i * j);
                printWriter.printf("%10d * %d = %d\n", j, i + 1, j
                        * (i + 1));

            }
            System.out.println("");

            printWriter.println("");
        }
        printWriter.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }}