0

I'm having trouble reading a two dimensional array format from file to my program. It's supposed to read the format like this and store each character as a class HvitRute or SvartRute depending on what character it is ('#' or '.') They both extend Rute.

Format:

13 13
#############
..#.........#
#.#######.###
#...#...#.#.#
###.#.#.###.#
#.#.#.#.....#
#.#.#.#######
#...#.......#
#.#########.#
#.#.........#
#.#.#######.#
#...#........
#############

Is there any logic error to my algorithm that im missing? Thanks! //Code starts here

Rute[][] labyrinth;

public void readFromFile(File file) throws Exception{
  Scanner in = new Scanner(file);
  String rows = in.nextLine();
  String[] size = rows.split(" ");
  int y = Integer.parseInt(size[0]); int x = Integer.parseInt(size[1]);
  labyrinth = new Rute[y][x];
  int index = 0;

  while(in.hasNextLine()){
    String inn = in.nextLine();
    int secondIndex = 0;

    for(int i = secondIndex; i < y; i++){
      switch(inn.charAt(secondIndex)){
        case '#': labyrint[index][secondIndex] = new HvitRute('#');
                  break;
        case '.': labyrint[index][secondIndex] = new SvartRute(' ');
                  break;
        default : System.out.println("Feil symbol");
                  break;
      }
      secondIndex++;
    }
    index++;
  }

for(int i = 0; i < y; i++){
  for(int k = 0; i < x; i++){
    if(labyrinth[i][k] != null){
      System.out.print(labyrinth[i][k].getType());
    } else {
      System.out.print("Error");
    }
    System.out.println();
  }
}

} }

4
  • please check using a println the x and y before the loop while and also check the inn string value Commented Mar 20, 2017 at 13:07
  • Using secondIndex in the for statement makes no sense. Should it not always start at 0 ? Commented Mar 20, 2017 at 13:09
  • Yeah, it could just as well be int i = 0, thanks. Commented Mar 20, 2017 at 13:22
  • What trouble are you having? A crash? Incorrect results? An infinite loop? Please detail your problem, including the output that you see, to give us a hint on where to look. Commented Mar 20, 2017 at 23:44

1 Answer 1

0

Should be:

for(int i = 0; i < y; i++){
  for(int k = 0; k < x; k++){
    ...
    ...
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah thanks @Strelok, it was just my for loop that was wrong!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.