在数组值之间打印空格

时间:2012-09-19 18:08:41

标签: java arrays project

我有这段代码,

else if (e.getSource() == saveButton) {
            Scanner scan;
            String es = " ";
            try {
                int status = chooser.showSaveDialog(null);
                if (status == JFileChooser.APPROVE_OPTION) {
                    File newImageName = chooser.getSelectedFile();
                    PrintWriter outFile = new PrintWriter(new FileWriter(newImageName));
                    outFile.print(drawing.typefile);
                    outFile.print(drawing.iname);
                    outFile.print(drawing.width);
                    outFile.print(es);
                    outFile.print(drawing.height);
                    outFile.print(drawing.maxshade);
                    for(int r = 0; r < drawing.array.length; r++)
                        for(int c = 0; c < drawing.array[r].length; c++)
                            outFile.print(drawing.array[r][c]);


            //      outFile.print(drawing.paintComponent(newImageName));
                    outFile.flush();
                    outFile.close();
                }
             else if (status == JFileChooser.CANCEL_OPTION) {
                }
            } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "File could not be written, try again.");
                    //ex.printStackTrace();
                }

        }

如何让它在值之间打印空格?   它打印

P2image1.pgm320 275255132132130125125128

我需要它打印

P2image1.pgm320 275255132 132 130 125 125 128

因此每个数组值之间都有一个空格,我尝试了很多东西,但我很困惑。

感谢。

3 个答案:

答案 0 :(得分:1)

只需在每个数字后明确打印一个空格。

你有没有试过像:

for(int r = 0; r < drawing.array.length; r++) {
    for(int c = 0; c < drawing.array[r].length; c++) {
        outFile.print(drawing.array[r][c]);
        outFile.print(" ");
    }
}

答案 1 :(得分:0)

outFile.print(drawing.array[r][c]);
outFile.print(" ");

答案 2 :(得分:0)

这里有很多答案说要这样做:

outFile.print(drawing.array[r][c]);
outFile.print(" ");

但是,我建议:

outFile.print(drawing.array[r][c] + " ");

它节省了大量空间,并使您的代码更具可读性!