Reputation: 296
I'm new to Java and am trying to create an array with objects read from a .txt file. The file looks something like this
Wall 2 2
Wall 3 4
Wall 3 5
.... and so on.
What I want to do is use the RandomAccessFile() function to fill an array[8][8] with the objects in the file, and in their appointed positions. I've been looking around but can't find a solution, or maybe I'm not looking in the right place. Any help will be appreciated.
EDIT:
I've made some progress (I think) and am able to read from the .txt file, however, I can't seem to assign objects to specific locations in my array... This is what I've got
public static void leer() throws IOException
{
Scanner s = new Scanner(new File("init.txt"));
while (s.hasNext())
{
if (s.next()=="Wall")
{
int i = s.nextInt();
int j = s.nextInt();
Tablero[i][j]=new Wall();
}
else if (s.next()=="Ghost")
{
int i = s.nextInt();
int j = s.nextInt();
Tablero[i][j]=new Ghost();
}
}
}
Now, I'm getting a "NoSuchElementException", which I gather means I'm not defining the Walls or Ghosts properly, and sadly, I don't quite understand the enum function... Again, any help would be great!
Upvotes: 0
Views: 9596
Reputation: 97661
This will work:
Scanner s = new Scanner(new File("map.txt"));
String[][] map = new String[8][8];
while (s.hasNext()) {
String value = s.next();
int x = s.nextInt();
int y = s.nextInt();
map[x][y] = value;
}
You might want to consider using an Enum to store the item in each cell:
public enum CellType {
EMPTY, WALL, POWERUP
}
Scanner s = new Scanner(new File("map.txt"));
CellType[][] map = new CellType[8][8];
while (s.hasNext()) {
String value = s.next().toUpperCase();
int x = s.nextInt();
int y = s.nextInt();
map[x][y] = CellType.valueOf(value);
}
You're calling .next()
twice in your code. You need to evaluate it only once, so only one token is consumed:
public static void leer() throws IOException {
Scanner s = new Scanner(new File("init.txt"));
while (s.hasNext()) {
//Read these at the top, so we don't read them twice, and consume too many tokens
String item = s.next();
int i = s.nextInt();
int j = s.nextInt();
if(item == "Wall") {
Tablero[i][j] = new Wall();
}
else if(item =="Ghost") {
Tablero[i][j]=new Ghost();
}
}
}
Upvotes: 1