二维数组跳过值

时间:2013-03-12 21:13:36

标签: java

我试图在一个文件中逐个字符地读入一个二维数组,并且我有一个代码可以执行该操作,但在读取第一行字符后,它不会对数组中的下一个空格设置任何内容然后设置应该在该空间中前方空间的字符。我该如何解决?

   for(int x = 0; ((c = br.read()) != -1) && x < w.length*w.length; x++) {
     w.currentChar = (char) c;
     w.row = x/w.length;
     w.column = x%w.length;
     w.wumpusGrid[w.row][w.column] = w.currentChar;
     System.out.print(w.currentChar);
     System.out.print(w.row);
     System.out.print(w.column);
   }

2 个答案:

答案 0 :(得分:1)

您的问题是正在读取行末尾的'\ n'并将其分配给您的数组,您需要跳过该字符并保留跳过的数量,以便为跳过的字符进行偏移:

int offset = 0;
for(int x = 0; ((c = br.read()) != -1) && x < w.length*w.length; x++) {
  if (c == '\n') {
    offset++;
    continue;
  }
  int pos = x - offset;
  w.currentChar = (char) c;
  w.row = pos/w.length;
  w.column = pos%w.length;
  w.wumpusGrid[w.row][w.column] = w.currentChar;
  System.out.print(w.currentChar);
  System.out.print(w.row);
  System.out.print(w.column);
}

答案 1 :(得分:0)

你的问题是在行尾('\n'(linux / mac)或'\r\n'(win))并将它们视为你的字符。尽管读取了char,但您正在增加x。从x++定义中的最后一部分中取出for,并将其移动到循环体的末尾。在循环的开始continue如果c == '\n' || c == '\r'(我猜两个字符对你都不感兴趣)

相关问题