在嵌套循环后无法让 PrintWriter 正确打印到 .text

Trouble getting PrintWritter to correctly print to .txt after my nested loop

我被要求使用 PrintWriter 将乘法问题的网格打印到 .txt 文件中。一切都运行良好,但我在让我的代码按照我要求的方式打印时遇到了一些严重的问题。我一直在使用带有 left/right 缩进的 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();
    }
   }
}

您没有写入 printWriter,而是仅写入控制台。也在内部 for 循环中写入 printWriter 对象以将内容存储在文件中。喜欢。

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