开发者

Issues of saving a matrix to a csv file

I am trying to save an integer matrix to the csv file. My code is listed as follows.

try
    {
      FileWriter writer = new FileWriter("test.csv");          
         for(int i = 0; i < row; i++)
         {
            for (int j=0; j<(开发者_运维技巧column-1); j++)
             {
                 writer.append(Matrix[i][j]);
                 writer.append(',');
             }
               writer.append(Matrix[i][j]);
               writer.append('\n');
               writer.flush();
         }
         writer.close();
      }        
    catch(Exception e)
    {
      e.printStackTrace();
    }

However, the Eclipse gives the following error message:

method append(CharSequence) in the type Writer is not applicable for the arguments (int)

How to solve this issue? Thanks.


Change your calls to append(Matrix[i][j]) to append(String.valueOf(Matrix[i][j]) or append("" + Matrix[i][j]). The problem (as the error message points out) is that you are attempting to append an integer, but the append method only take a CharSequence (i.e. a String). Both of the solutions I present coerce the integer/numeric type to a String.


As @I82Much mentioned, and an alternative is to use write (for ,, to avoid the creation of string). Also, you use j outside the for loop, so you need to declare it outside as well:

int j;
for (j=0; j<(column-1); j++)
{
    writer.append(Matrix[i][j]);
    writer.append(',');
}
writer.append(Matrix[i][j]);


The other answers are good, another way to do it is use

writer.append(Integer.toString(Matrix[i][j]));

Also as @MByD said you have to declare j outside the loop if you're using it outside the loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜