1

I made a multiplication table. The problem is that the table is not ordered as it should.

If I want just to print it on the screen, then I use this System.out.printf(“%4d”). How can I resolve this problem with BufferedWriter?

Instead of this:

Irj be egy szamot:
5
1 2 3 4 5 
2 4 6 8 10 
3 6 9 12 15 
4 8 12 16 20 
5 10 15 20 25 `

I want this:

Irj be egy szamot: 
5
1  2  3  4  5 
2  4  6  8 10 
3  6  9 12 15 
4  8 12 16 20 
5 10 15 20 25 `

Here is my code:

public class EgyszerEgy {
    public static void main(String[] args) {

        int a;
        int b;

        try {
            FileWriter writer = new FileWriter("EgyszerEgy.txt");
            BufferedWriter bf = new BufferedWriter(writer);

            Scanner tastatur = new Scanner(System.in);
            System.out.println("Irj be egy szamot: ");
            int szam = tastatur.nextInt();

            for (a = 1; a <= szam; ++a) {
                for (b = 1; b <= szam; ++b) {
                    int eredmeny = a * b;
                    String eredmenyString = String.valueOf(eredmeny);
                    bf.write(eredmenyString);
                    bf.write(" ");
                }
                bf.newLine();
            }
            bf.flush();
            bf.close();
        } catch (Exception e) {

        }

        // Kiolvasas
        //String result;
        try {
            FileReader fr = new FileReader("EgyszerEgy.txt");
            BufferedReader br = new BufferedReader(fr);
            String result;
            while ((result = br.readLine()) != null) {
                System.out.println(result);
            }
            br.close();
        } catch (Exception e) {

        }
    }
}
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
venndi
  • 161
  • 9

2 Answers2

4

You already know how to wrap a FileWriter with a BufferedWriter. Now wrap it again with a PrintWriter, which has the printf() methods.

You should also use try-with-resources. It was added in Java 7, so there is absolutely no good reason not to use it, unless you're stuck on Java 6 or earlier.

Same for using NIO.2 API instead of the old File I/O API.

Scanner tastatur = new Scanner(System.in);
System.out.println("Irj be egy szamot: ");
int szam = tastatur.nextInt();

try (PrintWriter fout = new PrintWriter(Files.newBufferedWriter(Paths.get("EgyszerEgy.txt")))) {
    for (int a = 1; a <= szam; ++a) {
        for (int b = 1; b <= szam; ++b) {
            int eredmeny = a * b;
            fout.printf("%3d ", eredmenyString);
        }
        fout.println();
    }
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
1

You can create the exact same formatting as printf by using String.format and writing the result to the BufferedWriter.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263