问题描述
for (i = 0; i < hourlyTemp.length; i++) {
System.out.print(hourlyTemp[i] + ",");
}
这会给我想要的输出,但以逗号结尾。如何在没有逗号结尾的情况下执行此操作? for-loop甚至有可能吗?
解决方法
轻松自在。
for(int i = 0; i < hourlyTemp.length; i++) {
System.out.print(hourlyTemp[i]);
if(i == hourlyTemp.length -1) break;
System.out.print(",");
}
,
您可以添加if
语句以打印逗号:
for (i = 0; i < hourlyTemp.length; i++) {
System.out.print(hourlyTemp[i]);
if(i != (hourlyTemp.length - 1)){
System.out.print(",");
}
}
,
如果不想在循环中使用条件以避免在数组较大的情况下进行条件检查,则可以使用以下代码:
for (i = 0; i < hourlyTemp.length - 1; i++)
{
System.out.print (hourlyTemp[i] + ",");
}
System.out.print (hourlyTemp[hourlyTemp.length - 1]);
,
我发现抑制前导逗号而不是尾随逗号更容易,因为我们不必使用length
来做到这一点:
for (i = 0; i < hourlyTemp.length; i++) {
if (i != 0)
System.out.print(",");
System.out.print(hourlyTemp[i]);
}
对于每个循环,您需要一个标志:
boolean first = true;
for (double temp : hourlyTemp) {
if (first)
first = false;
else
System.out.print(",");
System.out.print(temp);
}
您还可以用整行构建一个String
。这样会更好,因为print()
有一些开销:
StringBuilder buf = new StringBuilder();
for (double temp : hourlyTemp)
buf.append(",").append(temp);
if (buf.length() != 0)
System.out.print(buf.substring(2));
使用Java 8中添加的StringJoiner
更加容易:
StringJoiner buf = new StringJoiner(",");
for (double temp : hourlyTemp)
buf.add(String.valueOf(temp));
System.out.print(buf.toString());