在Java中导入文本文件并替换数组的值



我是Java初学者,在实践中有一步我应该将txt文件导入数组(使用JFileChooser(

文本格式如下001 839 333 426…

其中,每3个用空格分隔的字符对应于xyz,其中x=行号y=列编号v=值

我必须根据坐标(xy(替换板中的值

int [][] board =
{
{ 1, 0, 0, 0, 0, 0, 0, 0, 0 },  
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },          
{ 0, 0, 0, 0, 6, 0, 0, 0, 0 },          
{ 0, 0, 0, 3, 0, 0, 0, 0, 0 },          
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },          
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },          
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },          
{ 0, 0, 0, 0, 0, 0, 0, 0, 0 },          
{ 0, 0, 9, 0, 0, 0, 0, 0, 0 }
}

如果发现无效值,则不应将其用于例如901(因为没有可用的行9(。

欢迎任何帮助或想法。

对于那些最终感兴趣的人,我发现了一种进行转换的方法,它可能不是最佳的,但它是有效的:

public boolean loadFromFile(String path) {
try {
int x, y, v;
Scanner sc = new Scanner(new String());
Scanner file = new Scanner(new File(path));
while (file.hasNextLine()) {
String newLine = file.nextLine();
sc = new Scanner(newLine);
while (sc.hasNext()) {
String xyvalue = sc.next();
char[] xyv = xyvalue.toCharArray();
if (xyv.length == 3) {
x = Character.getNumericValue(xyv[0]);
y = Character.getNumericValue(xyv[1]);
v = Character.getNumericValue(xyv[2]);
if (x >= 0 && x < 9 && y >= 0 && y < 9 && v > 0 && v <= 9) {
board[x][y] = v;
}
}
}
}
sc.close();
file.close();
return true;
} catch (IOException exception) {
return false;
}

最新更新