I’m a beginner in Java and I'm stuck in one step in my practice where I should import an txt file into an array (using JFileChooser)
The text format is as follow 001 839 333 426 …
Where each 3 characters separated by space correspond to xyz where x= line number; y= column number; v= value
I have to replace the values in the board based on the coordinates (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 }
}
If an invalide value is found it should not be used for example 901 (because no line available 9).
Any help or thoughts are very welcome.
CodePudding user response:
For those interested finally, I found a way to do the conversion may be not the optimal, but it works:
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;
}