2017-06-12 24 views
0

我有一個名爲fields的二維數組,我需要能夠保存其內容(彩色首字母縮寫)。使用BufferedWriter&Loop保存來自2D JTextField數組的文本

try { 
    BufferedWriter outFile = new BufferedWriter(new FileWriter("Drawing_NEW.csv")); 
    for (int y = 0; y < totalY; y++) { 
     for (int x = 0; x < totalX - 1; x++) { 
      outFile.write(fields[x][y].getText() + ","); 
     } 
     outFile.write(fields[totalX - 1][y].getText()); 
     outFile.newLine(); 
    } 
    outFile.close(); 
} catch (Exception e) { 
    System.err.println("Error: " + e.getMessage()); 
} 

上面的代碼像這樣保存了所有數據。注意數組是20乘20(下面的輸出只是整個事情的一小部分)。

W,W,W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,W 
W,W,W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,W 

但我必須現在做一個循環,如果顏色是一樣的旁邊添加一個計數器,如果它沒有再寫入新的顏色,並設置計數器回1然後再次檢查爲下一個等等。下面是一個示例模板和它應該看起來像什麼的輸出。

(colour1,count1, colour2,count2, colour3,count3,) 

W,3,G,15,W,2 
W,3,G,3,Y,5,G,7,W,2 

隨時提問。謝謝。

回答

2

這意味着你需要添加一些狀態到你的循環來跟蹤以前的值。在你的例子中,AFAIU只需要爲數組中同一個「行」中相同字符串的序列編寫一個數字。如果是這樣的話,試試下面的代碼

for (int y = 0; y < totalY; y++) { 
    string prev = ""; // this value doesn't equal anything you can see in the UI, so the first iteration of the loop works as expected 
    int cnt = 0; 
    for (int x = 0; x < totalX - 1; x++) { 
     string cur = fields[x][y].getText(); 
     if(cur.equals(prev)) { 
      cnt ++; 
     } 
     else { 
      if(cnt > 0) // skip the first empty line 
       outFile.write(prev + "," + cnt + ","); 
      prev = cur; 
      cnt = 1; 
     } 
    } 
    // write the last sequence 
    outFile.write(prev + "," + cnt); 
    outFile.newLine(); 
} 
+0

關閉,但一些聲母在錯誤的地方正確的輸出應該是'W,3,G,15,W,2'但它給我'G,3, W,15 W,2'。這裏是[代碼](https://pastebin.com/A5hqmkVN)的鏈接 – Nicz

+0

@Nicz,請嘗試更新的代碼,我在'outFile.write'中使用'cur'而不是'prev' – SergGr

+0

非常感謝,它完美地工作。 – Nicz