John Smth John Smth - 1 month ago 14
Java Question

java writing patterns to a file

im having some trouble with one of my programs and was hoping the SO community could help. So I have this program tha asks the user to input a number. After they input the number the program will display a series of X's. An example is lets say that the user inputs 8. the program will display 8 x's in a row and colom like this:

XXXXXXXX

XXXXXXXX

XXXXXXXX

XXXXXXXX

XXXXXXXX

XXXXXXXX

XXXXXXXX

XXXXXXXX

So the issue im having is i need to write this to a file. I can only get it to print one line of X's. So if anyone can tell me how to make it so the diagram above will print to squares.txt that would be awesome.

import java.util.Scanner;
import java.io.*;
public class squareOutput {

public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a integer between 1 and 15");
int number = keyboard.nextInt();
while (number > 15 || number <1){
System.out.println("Sorry, thats a invalid number");
number = keyboard.nextInt();
}
keyboard.nextLine();
keyboard.close();
FileWriter fwriter = new FileWriter("square.txt", true);
PrintWriter outputFile = new PrintWriter(fwriter);

for (int r = 0; r < number; r++)
{


for (int c = 0; c < number; c++)
{
System.out.print("X");

outputFile.print("X");
}
outputFile.println("");
System.out.println("");



outputFile.close();
}
}


}

Answer

outputFile.close(); needs to be outside the for loop. You want to close the file only after all the writing is complete.

import java.util.Scanner;
import java.io.*;
public class squareOutput {

public static void main(String[] args) throws IOException  {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please enter a integer between 1 and 15");
    int number = keyboard.nextInt();
    while (number > 15 || number <1){
        System.out.println("Sorry, thats a invalid number");
        number = keyboard.nextInt();
    }
        keyboard.nextLine();
    keyboard.close();
    FileWriter fwriter = new FileWriter("square.txt", true);
    PrintWriter outputFile = new PrintWriter(fwriter);

        for (int r = 0; r < number; r++)
        {


            for (int c = 0; c < number; c++)
            {
                System.out.print("X");

                outputFile.print("X");
            }
            outputFile.println("");
            System.out.println("");



            // outputFile.close(); <-- NOT HERE
        }
        outputFile.close(); // <-- HERE
    }   
}
Comments