导入文本文件并替换 Java 中的数组值
Import a text file and replace a values of an array in Java
我是 Java 的初学者,我在练习中卡住了一步,我应该将 txt 文件导入数组(使用 JFileChooser)
文字格式如下
001 839 333 426 …
其中由space分隔的每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;
}
我是 Java 的初学者,我在练习中卡住了一步,我应该将 txt 文件导入数组(使用 JFileChooser)
文字格式如下 001 839 333 426 …
其中由space分隔的每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;
}