0

I know this is probably very basic but I have been trying for hours and still can't figure this out on my own. So right now I am doing the 8 puzzle game for my AI class. I need the user to enter a series of numbers, say: "032 145 678" and I need to simply store this into a 3x3 matrix, where 0 will basically represent an empty block. So it should take that user input and store it like {{032},{145},{678}}, a 3x3 matrix.

EDIT:

public void ReadFromTxt(String file) throws FileNotFoundException, IOException {
    String read; 
    FileReader f = new FileReader(file);
    int i = 0;
    int j;
    BufferedReader b = new BufferedReader(f);
    System.out.println("Loading puzzle from file...");
    while((read = b.readLine())!=null){
        if(read.length()==3){
            for(j=0;j<3;j++){
                board[i][j] = (int)(read.charAt(j)-48);
            }
        }
        i++;
    }
    b.close();
    System.out.println("Puzzle loaded!");
}
  • What is the programming language? And, when you say "numbers", a number is something like "145". The lone "1" is a "digit" here. Do you want to store numbers or only digits between 0 and 9, in your matrix? – Mark Galeck Sep 30 '16 at 21:26
  • The language is Java, sorry should've specified. Only numbers 0-9, so it would be like a 3x3 matrix with 0 3 2, 1 4 5, 6 7 8 – thetemptations Sep 30 '16 at 21:33

1 Answers1

0

The best way is to have the user store the digits in a text file. The text file format is, 3 lines, each line must have 3 digits only, and the digits begin at at the start of each line.

Your program should take the name of the file, where the digits are stored, as the argument.

The program allocates itself a 3x3 array of unsigned integers, opens the file, and reads each line in turn. It checks that the format of the line is correct: must have 3 digits at the beginning, whitespace after that is allowed. If not correct, program prints an error message to the user and exits.

If the format of the line is correct, the digits are stored into a row of the array.

If there are more than 3 lines, again, the program prints an error message and exits.

Mark Galeck
  • 6,155
  • 1
  • 28
  • 55
  • So I made an edit above, would something like that work? If i do put it in a text file, what should I name the file and where should I put it? – thetemptations Sep 30 '16 at 21:44
  • I can't debug your program for you until you have tried to debug yourself, found all bugs you can find, and isolated the remaining ones, if any. In the process you will learn greatly. You can then post the isolated bugs here. As for the name, you can name it anything and put it anywhere, where your program can access it. – Mark Galeck Sep 30 '16 at 21:50