I am trying to write an writer in Java which takes integer values out of an ArrayList for the first row and column and a float[][] for the rest and formats it into a CSV. Doing this my first column gets weird and I can’t find the problem. I would be really happy for any suggestions or help. Here is my code:
public static void resulttofile(List<Nm_item> nmvector,
float[][] cor_matrix, String filename) {
try {
FileWriter writer = new FileWriter(new File(filename + ".csv"));
for (int i = nmvector.get(0).row; i <= nmvector
.get(nmvector.size() - 1).row; i++) {
writer.write(sepw + nmvector.get(i).nm);
}
writer.write(System.getProperty("line.separator"));
for (int i = nmvector.get(0).row; i <= nmvector
.get(nmvector.size() - 1).row; i++) {
writer.write(nmvector.get(i).nm);
for (int j = nmvector.get(0).row; j <= nmvector.get(nmvector
.size() - 1).row; j++) {
writer.write(sepw + cor_matrix[i][j]);
}
writer.write(System.getProperty("line.separator"));
}
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Results saved to " + filename + ".csv");
}
and the output (cropped):
350 351 352 353
? 0 0.003 0.171 0.001
? 0.003 0 0.274 0
è 0.163 0.271 0 0.345
Ü 0 0 0.35 0
? 0.008 0.019 0.326 0.044
? 0.008 0.016 0.199 0.015
? 0.015 0.037 0.361 0.04
? 0.029 0.023 0.171 0.023
? 0.038 0.042 0.186 0.038
Try:
Or, as OldCurmudgeon says:
The point is that FileWriter contains more than one
writemethod. There is write(int) and write(String). The first one doesn’t write the number, it writes the character that corresponds to the number given, so for examplewriter.write(88)will output the character ‘X’,writer.write(89)will output ‘Y’, and you can guess whatwriter.write(90)will give you. You need to convert the integer to a String so that the rightwrite()method is called.The second form
writer.write("" + number)works because when you add a number to a String the Java compiler will automatically convert the number into a String for you. This is whywriter.write(sepw + nmvector.get(i).nm);works butwriter.write(nmvector.get(i).nm);doesn’t.