使用 BufferedWriter & Loop 从 2D JTextField 数组保存文本
Save text from 2D JTextField array using BufferedWriter & Loop
我有一个名为 fields
的二维数组,我需要能够保存其内容(颜色首字母)。
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 x 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
欢迎提问。谢谢。
这意味着您需要向循环添加一些状态以跟踪以前的值。根据您的示例,您只想为数组的相同 "line" 中相同字符串的序列写一个数字。如果是这样,请尝试以下代码
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();
}
我有一个名为 fields
的二维数组,我需要能够保存其内容(颜色首字母)。
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 x 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
欢迎提问。谢谢。
这意味着您需要向循环添加一些状态以跟踪以前的值。根据您的示例,您只想为数组的相同 "line" 中相同字符串的序列写一个数字。如果是这样,请尝试以下代码
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();
}