Search code examples
javalinemultiplication

Java multiplication table, Writer writes in second line instead of first


It's supposed to be a multiplication table in the shape of a square, but the writer doesn't write the numbers in the first line and the first column.

try {
    File file = new File("multi.txt");
    // FileWriter Writer = new FileWriter("multi.txt");

    BufferedWriter Writer = new BufferedWriter(new FileWriter(file));
        
    for (int o = 1; o <= n; o++) {
        Writer.write ("\n");
        for (int s = 1; s <= n; s++) {
            if (o * s < 10) Writer.write( " ");
            if (o * s < 100) Writer.write( " ");
            // System.out.print( "  " + z * s);
            Writer.write ("    " + o * s);
        }
    }
    Writer.close();

Solution

  • This should do it:

    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    
    public class tmp {
    
        public static void main(String[] args) {
    
            try {
    
                File file = new File("multi.txt");
                // FileWriter Writer = new FileWriter("multi.txt");
    
                BufferedWriter Writer = new BufferedWriter(new FileWriter(file));
                int n = 10;
                
                for(int o = 1; o <= n; o++) {
                    for(int s = 1; s <= n; s++) {
                        Writer.write(o*s+"\t");
                    }
                    Writer.write("\n");
                }
                Writer.close();
            } catch (Exception e) {
                System.out.println("exception thrown");
            }
        }
    }