2013-03-12 121 views
-1

我想讀一個文件到一個字符的二維數組字符,我有一個代碼,這樣做,但在讀取第一行字符後,它什麼都沒有設置到下一個空間在陣列中,然後將應該在該空間中的角色設置在前一個空間中。我如何解決它?二維數組跳過值

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); 
    } 
+0

什麼是'w'?一個東西? – Makoto 2013-03-12 21:18:46

+0

顯然w表示Hunt the Wumpus遊戲的當前狀態。 :) 更多這裏:http://en.wikipedia.org/wiki/Hunt_the_Wumpus – 2013-03-12 21:21:50

回答

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); 
} 
+0

我建議使用BufferedReader從源文件一次讀取一行,然後逐個構建數組的每一行,然後。 – 2013-03-12 21:59:18

0

你的問題是行尾('\n'(的Linux/Mac)或'\r\n'(WIN)),並把他們當作你的字符。儘管讀了什麼字符,你正在增加x。在for定義的最後部分中取x++,並在循環體的末尾移動它。在循環的開始continue if c == '\n' || c == '\r'(我猜這兩個字符對你都不感興趣)