如何从输入文件中的一行数字中逐个读取数字



基本上,我必须获取一个输入文件并填写一个9乘9的数组,但输入必须看起来像

530070000
600195000
098000060
800006003
400803001
700020006
060000280
000419005
000080079

数字没有分开,但我需要把每个数字都填写9x9数组,以制作一个看起来像数独游戏的数组。我不知道如何逐个读取输入的数字,这意味着第一行的第一个int是5,然后下一个int是3,然后是0,依此类推

public class SudokuChecker 
{
public static void main(String[] args) throws Exception 
{

File file = new File("in.txt");
Scanner in = new Scanner(file);

int [][] array = new int [9][9];
while(in.hasNextLine()) 
{
for (int i=0; i<array.length; i++) 
{
String[] line = in.nextLine().trim().split(" ");

for (int j=0; j<line.length; j++) 
{
array[i][j] = Integer.parseInt(line[j]);
}
}
}
}  
}

板看起来像

这里有一个解决方案,它将读取当前行并将数字放入9x9数组中。这只对每一行执行,并且在随后的行读取中将清除数组。OP必须完成代码以处理后续的行读取。

这利用try-with-resourceBufferedReader来读取每一行,而不是扫描器。然后它将读取该行。拆分space上的行,然后将子字符串中的每个项转换为字符数组并对其进行迭代。然后,它会将该值转换为一个整数,并将其存储到数组中。

public static void main(String[] args) throws IOException {
int[][] sudoku = new int[9][9];
try (BufferedReader reader = Files.newBufferedReader(Paths.get("in.txt"))) {
String line = null;
int row = 0;
while ((line = reader.readLine()) != null) {
int col = 0;
for (char c : line.toCharArray()) {
sudoku[row][col++] = Integer.valueOf(Character.toString(c));
}
row++;
}
}
}

最新更新