Hello,
This is my first post on DaniWeb and will probably not be the last so I hope I'm doing this right:

I'm currently working on a Sudoku Solver that allows the user to type in the name of a Sudoku text file that looks like this:

6 8 . . . . . 5 .
. . . . . 5 . . .
. . 3 8 . . 2 6 .

1 . 7 . 2 . . . .
. . 9 5 . 8 6 . .
. . . . 1 . 7 . 2

. 2 1 . . 9 4 . .
. . . 4 . . . . .
. 3 . . . . . 2 8

and then the data will be read in to a 2D array and solved from there. I have tried many different ways to do this from using a Scanner to a BufferReader etc., but the way I have it now that a TA suggested was to read the file from a Scanner, put the file in as a parameter for a Sudoku object and then read the data from there. But everytime I run the program, it runs in to an infinite loop and doesn't do anything.... I wasn't sure if it has something to do with the code I have or where the files are being stored because every other idea I have tried to accomplish this has produced File Not Found errors. I have posted the Sudoku Application class I have (hope these code tags work :) ):

public class SudokuApp
{
    public static void main (String[] args) throws IOException
    {
        Scanner glaDOS = new Scanner (System.in);
        System.out.print("PLEASE ENTER A VALID FILE NAME THAT CONTAINS A SUDOKU: ");
        File sudokuFile = new File (glaDOS.next());
        Sudoku puzzle = new Sudoku (glaDOS);
        System.out.println ("Unsolved: ");
        System.out.println (puzzle);
        System.out.println ("Solved: " );
        System.out.println (puzzle);
        System.out.println("Backtracking steps: ");
        
  
    }

And the Sudoku constructor class I currently have that puts the data in to a 2D array:

public Sudoku (Scanner sudokuReader) 
    {
        int[][] puzzle = new int[9][9];
        
        for (row = 0; row < 9; row++)
        {
            for (col = 0; col < 9; col++)
            {
                if(sudokuReader.hasNextInt())
                {
                    num = sudokuReader.nextInt();
                    this.puzzle[row][col] = num;
                    col++;
                    if (col == 8)
                        row++;
                }
                else
                if (row == 8)
                    return;
            }
            
        }

I am really enjoying being part of this community so far, am looking forward to responses and Thank You to all for your help!

Recommended Answers

All 13 Replies

Your current code is passing your System.in scanner to your Sudoku constructor. You need to create a new scanner for your input file and that is the one you want to pass to your constructor.

Once you get that part working, you have a bit of work to do on the logic of your loops to populate the puzzle array.

OK, Thanks! That's what I thought to do at first. I had a similar problem with a maze solver that I created and that was how I fixed it. I've modified it now so I now have in the Sudoku app:

File sudokuFile = new File (glaDOS.next());
        [B]Scanner glaDOS2 = new Scanner (sudokuFile);
        Sudoku puzzle = new Sudoku (glaDOS2);[/B]

But then when I try to run it like that, I come up with this error:

PLEASE ENTER A VALID FILE NAME THAT CONTAINS A SUDOKU: puzzle1.txt

Exception in thread "main" java.io.FileNotFoundException: puzzle1.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at assignment03.SudokuApp.main(SudokuApp.java:25)

(puzzle1.txt being the file that is read) That's why I wasn't exactly sure if that was the right way to do it. I thought it had something to with where the puzzle was in relation to the .Java files (in the same folder in this case with Eclipse), but I'm not sure why I'm getting that error or how to fix it in the code........

It's actually relative to whatever your projects "current working directory" is, which I am not sure what that is by default in Eclipse. You could try placing a copy of that file in your project's root directory (not the src directory). Or you could just specify the full path to the file.

I'm not quite sure what you mean by the project's root directory....although the path for the current .Java file is:

Desktop/CS Programs/CS 2410/CS 2420/src/assignment03/SudokuApp.java

and the puzzle1.txt file and Sudoku/SudokuApp java files are all in the same directory...

I have tried copying them to the .metadata/org.eclipse.core.resources/.root folder if that's what you mean and tried running the program with the puzzle files in there and I still get the same error.....it's weird. I actually tried the exact same code in BlueJ and I put the puzzle files in there along with the .java files and it read the file fine (although there was a null pointer exception that had to do with the logic you discussed in the Sudoku constructor :) )...so I know it has something to do with Eclipse....I'm just not sure what.....

I'm think you can set the working directory through the project properties in Eclipse, but I don't have it here to look myself. I would think the root working directory would be "Desktop/CS Programs/CS 2410/CS 2420" but that may not be the case.

Ok, since my last post I have made a lot of progress. I have the code reading the data all right and I think I have the solve and IsLegal method done, but for some reason either in the ToString method or in the constructor itself, it's printing out the output funny like so:

PLEASE ENTER A VALID FILE NAME THAT CONTAINS A SUDOKU: puzzle2.txt
Unsolved:
6800000500000050000038002601070200000095086000000107020210094000

when in reality the output should be this:

Enter the name of a Sudoko puzzle file: puzzle2.txt

Unsolved:
6 8 . . . . . 5 .
. . . . . 5 . . .
. . 3 8 . . 2 6 .

1 . 7 . 2 . . . .
. . 9 5 . 8 6 . .
. . . . 1 . 7 . 2

. 2 1 . . 9 4 . .
. . . 4 . . . . .
. 3 . . . . . 2 8

although the periods are going to be zeroes just to make it easier for the solve method to go through the data. I'm not sure why it is printing it out like that....here is the code for the Sudoku class I currently have:

package assignment03;

import java.io.*;
import java.util.Scanner;

/**
 * This class represents a Sudoku object and 
 * contains the Solve and Legal move methods 
 * necessary to move through the puzzle itself
 * using a backtracking algorithm and solve it.
 * 
 * @author Michael Goleniewski
 *
 */


public class Sudoku
{
    //instance variables
    private int number;
    private int [][] puzzle;
    private int bsteps;
    /**
     * 
     * @param sudokuReader the scanner containing the puzzle
     * file to be read and scanned into an array
     * @throws IOException 
     * 
     */
    public Sudoku (Scanner sudokuReader) 
    {
        puzzle = new int [9][9];
        
        for (int row = 0; row < 8; row++)
        {
            for (int col = 0; col < 8; col++)
            {
                    if(sudokuReader.hasNextInt())
                    {
                        number = sudokuReader.nextInt();
                        puzzle[row][col] = number;
                    }
                    else
                        sudokuReader.next();
                }
             }
    }
    /**
     * Returns the number of Backtracking steps needed
     * to solve the sudoku puzzle.
     * @return bsteps the number of backtracking steps
     */
    public int getBacktrackingSteps()
    {
        return bsteps;
    }
    /**
     * Method that checks to see if a number can be put in to
     * a specific position on the Sudoku board
     * @param row row position
     * @param col column position
     * @param num number being analyzed
     * @return value stating if the move is legal
     */
    public boolean isLegal (int row, int col, int num)
    {
        for(int i = 0; i < 9; i++)//checks for the same values row-wise
            if (num == puzzle[i][col])
                return false;
        
        for(int j = 0; j < 9; j++)//checks for the same values column-wise
            if (num == puzzle[row][j])
                return false;
                
        int boxR = (row/3) * 3;
        int boxC = (col/3) * 3;
        for(int m = 0; m < 3; m++)//checks 3x3 boxes
        {
            for (int n = 0; n < 3; n++)
            {
                if (num == puzzle[boxR + m][boxC + n])
                    return false;
            }
        }
            
         
         return true; //no violations, so legal
    }
    
    /**
     * Methods that uses a backtracking algorithm to put
     * numbers into positions on the puzzle and tries to
     * solve it. If there is a solution, it returns true.
     * If there is no solution, it returns false.
     * @param row row position to start solving from
     * @param col column position to start solving from
     * @return value boolean stating if puzzle can be solved
     */
    public boolean solve (int row, int col)
    {
        if(++row == 8)
            return true;
        if (puzzle[row][col] == 0)
            return(solve(row++, col++));
        for(int num = 1; num <= 9; ++num)
        {
            if(isLegal(row, col, num))
            {
                puzzle[row][col] = num;
                bsteps++;
                if(solve(row, col++))
                    return true;
            }
        }   
            return false;
        
            
    }
    
    /**
     * Returns a string representing the contents of the
     * sudoku.
     * @return string representation of the puzzle
     */
    public String ToString()
    {
        String puzprint = "";
        for (int row = 0; row < 8; row++)
        {
            for(int col = 0; col < 8; col++)
            {
               System.out.print(puzzle[row][col]);
               
            }
        }
        return puzprint; 
        
    }

}

Thanks once again for helping me get this far.....

You just need to terminate the line of output after each row with System.out.println(); .

so jmchurch is ur assignment work? can u post the solver here??

Do not hijack old threads merely to post "give me teh codez". If you have a question about an assignment, start a new thread and post the code that you have as a start.

hi, I am new student studying programing and i am struggle in my first assignment. The assignment is to create a mini sudoku game. The goal of this game is to fill a 4x4 grid of numbers so that each column, each row and each of the four 2x2 boxes (called regions) contains all of the numbers from 1 to 4. Using blueJ.
Can someone help out please.

Read this:

Do not hijack old threads merely to post "give me teh codez". If you have a question about an assignment, start a new thread and post the code that you have as a start.

hey
i have a problem.
we now must "write! a sudoku in blueJ but i dont now how to.
can you please help me?!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.