for (i = 0; i < hourlyTemp.length; i++) {
System.out.print(hourlyTemp[i] + ", ");
}
this would give me the output that I want but with a comma the end. How can I do this without the comma at the end? is it even possible with a for-loop?
If you don't want if condition inside a loop to avoid condition checking in case of larger array, you can use code below:
for (i = 0; i < hourlyTemp.length - 1; i++)
{
System.out.print (hourlyTemp[i] + ", ");
}
System.out.print (hourlyTemp[hourlyTemp.length - 1]);
Easy peasy.
for(int i = 0; i < hourlyTemp.length; i++) {
System.out.print(hourlyTemp[i]);
if(i == hourlyTemp.length -1) break;
System.out.print(",");
}
I find that suppressing a leading comma, instead of a trailing comma, is easier, since we don't have to use length
to do so:
for (i = 0; i < hourlyTemp.length; i++) {
if (i != 0)
System.out.print(", ");
System.out.print(hourlyTemp[i]);
}
With a for-each loop, you'd need a flag:
boolean first = true;
for (double temp : hourlyTemp) {
if (first)
first = false;
else
System.out.print(", ");
System.out.print(temp);
}
You can also build a String
with the entire line. That would perform better, since print()
has some overhead:
StringBuilder buf = new StringBuilder();
for (double temp : hourlyTemp)
buf.append(", ").append(temp);
if (buf.length() != 0)
System.out.print(buf.substring(2));
Using the StringJoiner
added in Java 8 is even easier:
StringJoiner buf = new StringJoiner(", ");
for (double temp : hourlyTemp)
buf.add(String.valueOf(temp));
System.out.print(buf.toString());
you could add an
if
statement for printing comma: