0
public class tabular {
    public static void main(String[] args)
    {
        for (int row = 0; row < 4; row++)
        {   

            for (int col = 0; col < 4; col++)
            {
                System.out.print(row + "" + col + "\t" );
            }
            System.out.println("\n");
        }
    }
}

This is my code and my task is modify this program and print this into a file. What does it means to turn this program to file? what i learned before was open file from file reader or use printwriter to make a file.

Bernhard Barker
  • 50,899
  • 13
  • 85
  • 122
  • Please add the tags for the language you are using in future when asking questions. – cs95 Sep 19 '17 at 19:31
  • Now modify your program so it prints the table to a file. Use the .dat extension on your file name. I don't understand what is the task is asking for. – user8636381 Sep 19 '17 at 19:46
  • 1
    It kind of sounds like you need English lessons more than programming lessons. "open file from file reader or use printwriter to make a file" - this is exactly what they are asking you to do. If you don't understand your assignment, the best person to ask about it is probably your teacher. – Bernhard Barker Sep 19 '17 at 19:48

2 Answers2

0

You are currently printing the output to the screen via System.out.prin()

See: How do I create a file and write to it in Java?

gdlamp
  • 537
  • 1
  • 5
  • 23
  • this is code for part one of my assignment(.Now modify your program so it prints the table to a file. Use the .dat extension on your file name). And this is for part two but i don't understand what is it asking for me to do. – user8636381 Sep 19 '17 at 19:47
  • just replace your "System.out.println" with “writer.println”, etc – gdlamp Sep 19 '17 at 19:51
0

You just need to create a PrintWriter and replace the default output System.out by the new output pw

public static void main(String[] args) throws FileNotFoundException {

    PrintWriter pw = new PrintWriter(new FileOutputStream("file.txt"));

    for (int row = 0; row < 4; row++) {
        for (int col = 0; col < 4; col++) {
            pw.print(row + "" + col + "\t");
        }
        pw.println("\n");
    }
    pw.close();   // it calls flush() method to push the data in the file
}

The file will be created in the current directory, you can change the path of course

azro
  • 35,213
  • 7
  • 25
  • 55
  • I think this is what i needed to do for this assignment, my mind is too straight forward because in textbook it only teaches how to string the data into file. Thank you so much for pointing it out for me. – user8636381 Sep 19 '17 at 19:59