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?

4

There are 4 best solutions below

0
On

you could add an if statement for printing comma:

for (i = 0; i < hourlyTemp.length; i++) {
    System.out.print(hourlyTemp[i]); 
    if(i != (hourlyTemp.length - 1)){
        System.out.print(", ");
    }
}
0
On

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]);
0
On

Easy peasy.

for(int i = 0; i < hourlyTemp.length; i++) {
    System.out.print(hourlyTemp[i]);
    if(i == hourlyTemp.length -1) break;
    System.out.print(",");
}
0
On

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());