I want to print out the values in this array of sorts with each value being comma separated in java. However, I do not want my last value to have a comma after it.
for (double val : output.getPvalues())
{
System.out.print(val + ",");
}
Right now, my output looks like this and I don't want the comma at the end.
0.3151985084814564,0.12439565272818136,0.08395574717762709,
0.23648887465370277,0.13987884822617208,0.1316174439685804,
0.23774083903133078,0.14471871035755607,0.16040529724318148,
0.23138041484992727,0.12692146250237307,0.10444029009575935,
Sorry it's my first day in java, and I don't know how to find the length of this object. How can I do it?
If output.getPvalues()
returns an array, you could use:
double[] values = output.getPvalues();
for (int i = 0; i < values.length(); i++) {
System.out.print(values[i]);
if (i != values.length - 1) {
System.out.print(",");
}
}
Or to make the condition simpler, you could just print a comma before all but the first item - at which point you can go back to an enhanced-for loop, because it's easy to tell if you're in the first iteration:
boolean firstIteration = true;
for (double value : output.getPvalues()) {
if (firstIteration) {
firstIteration = false;
} else {
System.out.print(",");
}
System.out.print(values[i]);
}
Alternatively, if you're using Java 8, you could use streams and Collectors.joining
- but that's rather more advanced.
See more on this question at Stackoverflow