繁体   English   中英

Java 数独帮助:如何将数独字符串转换为 2d int?

[英]Java Sudoku help: How can i turn my sudoku string to a 2d int?

我正在编写代码来检查数独板是否是获胜板。 我将电路板作为文件读取并存储在字符串中。 那个字符串就是我通过方法来读取它、打印它,然后检查板是否是获胜板。 无论是否存在,它都会打印出来。 我一直在尝试将 String 转换为 2d int 数组,以便对其进行检查。

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

public class lab{
public static void main(String args[])throws Exception{
    File file = new File("sudoku.txt");
    readSudoku("C:\\Users\\offda\\Desktop\\CS2 Week 1\\sudoku.txt");

}
public static void readSudoku(String str)throws Exception{

    Scanner sc = new Scanner(new File("C:\\Users\\offda\\Desktop\\CS2 Week 1\\sudoku.txt"));

    try{
        FileReader fileR = new FileReader("sudoku.txt");
        BufferedReader br = new BufferedReader(fileR);

        while((str=br.readLine())!=null){       
            printSudoku(str);
        }

        br.close();

    }catch(IOException e){
        System.out.println("Error loading board...");
    }

}
public static void printSudoku(String str){
    System.out.println(str);

    //checkSudoku(str);

}
/* 
public static boolean checkSudoku(int[][] str){
    for(int i=0; i<str.length;i++){
        int[] r= new int[9];
        int[] s = new int[9];
        int[] c = str[i].clone();
        for(int j=0;j<str[i].length;j++){
            r[j]=str[j][i];
            s[j]=str[(i/3)*3+j/3][i*3%9+j%3];               
        }
        if(!(validate(c)&&validate(r)&&validate(s))){
            System.out.println("losing board!");
            return false;
        }
        else{
            System.out.println("winning board!");
        }
    }
    return true;
}
public static boolean validate(int[] val){
    int v=0;
    Arrays.sort(val);
    for(int n = 0;n<val.length;n++){
        if(n!= v++){
            return false;
        }   
    }
    return true;
  }
*/
}

/*heres my board (txt):
4 8 3 9 2 1 6 5 7 
9 6 7 3 4 5 8 2 1 
2 5 1 8 7 6 4 9 3 
5 4 8 1 3 2 9 7 6 
7 2 9 5 6 4 1 3 8 
1 3 6 7 9 8 2 4 5 
3 7 2 6 8 9 5 1 4 
8 1 4 2 5 3 7 6 9 
6 9 5 4 1 7 3 8 2
*/

我将用 5 个测试用例运行它,每个测试用例都应该打印整个板以及它是否赢得数独。

int x = 0;
int[][] sudoku = new int[9][9];
while((str=br.readLine())!=null){       
    printSudoku(str);
    for (int y=0;y<9;y++) {
        sudoku[x][y] = Character.getNumericValue(str.charAt(x*9+y));
    }
    x++;
}

在此之后, sudoku变量将包含数独(假设您的文本文件包含 9 行 9 个数字,其中没有空格或其他文本)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM