2

I have to add a matrix of a sudoku to a text-file, I have this code that allows me to save strings, I need to adapt it to save a two-dimensional array (matrix).

How can I adapt my code so it can save a matrix?

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SudokuProject {

    public static void main(String[] args) {
        try {
            BufferedWriter textfile
               = new BufferedWriter(new FileWriter("path\\test.txt"));
            textfile.write("Hello");
            textfile.close();
        } catch (IOException ex) {
            Logger.getLogger(SudokuProject.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
0

1 Answer 1

3

Try this:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

public class SudokuProject {
    public static void main(String[] args) {
        int[][] sudokuNumbers = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        try (
                PrintStream output = new PrintStream(new File("output.txt"));) {
            for (int i = 0; i < sudokuNumbers.length; i++) {
                String s= "";
                for (int j = 0; j < sudokuNumbers[i].length; j++) {
                    s+= "|" + sudokuNumbers[i][j] + "|";
                }
                output.println(s);
            }
            output.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

It will generates this file structure:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.