【问题标题】:Save text from 2D JTextField array using BufferedWriter & Loop使用 BufferedWriter & Loop 保存二维 JTextField 数组中的文本
【发布时间】:2017-06-12 08:07:31
【问题描述】:

我有一个名为 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(下面的输出只是整个事物的 sn-p)。

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

随时提问。谢谢。

【问题讨论】:

    标签: java arrays loops bufferedwriter


    【解决方案1】:

    这意味着您需要在循环中添加一些状态来跟踪以前的值。在您的示例中,您只想为数组的同一“行”中的同一字符串的序列编写一个数字。如果是这样,请尝试以下代码

    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();
    }
    

    【讨论】:

    • 关闭,但一些首字母的位置错误,正确的输出应该是W,3,G,15,W,2,但它给了我G,3,W,15,W,2。这是code的链接
    • @Nicz,请尝试更新代码,我在outFile.write 中使用cur 而不是prev
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    相关资源
    最近更新 更多