-1

I am working on an assignment to produce sudoku in Java. I have been given 81 values in the form of a string [9] by [9] just as in Sudoku. I need to break this string into 9 arrays of 9 and convert the individual character into an integer.

e.g. I have the following :

public static String candidateSolution = "735684291628591347194327865213869574876245139459173682367412958981756423542938716";

I was thinking to do a for loop where every 9 values it copies it to a new array index.

I have managed to get this far to output an entire 9x9 array but no values are inside.

My array declaration

public static int rows = 9;
public static int columns = 9;
public static int[][] sudokuGrid = new int[rows][columns];

My conversion of string to array

public void convertToArray(String candidateSolution){
    for(int i = 0; i < 9; i++){
        for(int j = 0; j < 9; j++){
            sudokuGrid[i][j] = 
Character.getNumericValue(candidateSolution.charAt(i));
        } 

    }
}

My current output is

[[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], ect...

2 Answers2

0

You can use the text.charAt () function; - using a for loop, enter single digits into the array, or using 2 nested for loops, one digit to one [] and the other to the other []. If I have not described the topic very comprehensively, in the following link you have more information Get string character by index - Java

If it was not the case, specify the question, show the code, what you got stuck in, what you did and I will try to help;)

  • This wasn't exactly what I meant. I managed to convert the array but no values are being placed inside it. – Lee Stevens Dec 02 '17 at 18:45
  • iterate through the empty string public void convertToArray(String candidateSolution){ this .candidateSolution= candidateSolution; for(int i = 0; i < 9; i++){ for(int j = 0; j < 9; j++){ sudokuGrid[i][j] = Character.getNumericValue(candidateSolution.charAt(i)); } } } – PatrycjaMirko Dec 02 '17 at 19:59
  • Character.getNumericValue(candidateSolution.charAt(j)); no i , just j ;) – PatrycjaMirko Dec 02 '17 at 20:09
0

Please refer to Is an array a primitive type or an object (or something else entirely)?

It seems arrays are objects created by the JVM directly. Your array is populated during the function call, but it might be that the actual array in the calling function is not referred at all.

Also you need an integer that is incremented every time the inner loop is executed. Otherwise, the first value of a row will be assigned to each column of the row.

chb
  • 1,727
  • 7
  • 25
  • 47