如何打印列表末尾没有逗号? [英] How do I print the list out without a comma at the end?
本文介绍了如何打印列表末尾没有逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码输出应以最后一个元素结尾,结尾不带逗号或空格.我无法弄清楚如何阻止它的发生.
我尝试过的事情:
My codes output should end with the last element, without a comma or space at the end. I''m having trouble figuring out how to stop it from happening.
What I have tried:
import java.util.Scanner;
public class PrintWithComma {
public static void main (String [] args) {
final int NUM_VALS = 4;
int[] hourlyTemp = new int[NUM_VALS];
int i;
hourlyTemp[0] = 90;
hourlyTemp[1] = 92;
hourlyTemp[2] = 94;
hourlyTemp[3] = 95;
for(i = 0; i < NUM_VALS; i++)
{
System.out.print(hourlyTemp[i] + ", ");
// if (i <= NUM_VALS)
// {
// System.out.print(", ");
//}
}
System.out.println("");
}
}
推荐答案
两种方式:
第一种是手动将分隔符放在第二个及后续项目的前面:
Two ways:
The first is to manually put the separator in front of the second and subsequant items:
for(i = 0; i < NUM_VALS; i++)
{
if (i > 0)
System.out.Print(", ");
System.out.print(hourlyTemp[i]);
}
还有许多其他方式可以执行该代码,但这是最清晰的.
另一种是使用Join函数: ^ ]然后打印出来.
There are many other ways to do that code, but that''s the clearest.
The other is to use a Join function: What''s the best way to build a string of delimited items in Java? - Stack Overflow[^] And then print that.
假设至少要打印1个项目,我这样做:
Assuming there is at least 1 item to print, I do this way:
System.out.print(hourlyTemp[0]);
for(i = 1; i < NUM_VALS; i++)
{
System.out.print(", " + hourlyTemp[i]);
}
通过这种方式,它消除了在循环内进行测试的需要.
By doing this way, it remove the need to have a test inside the loop.
这篇关于如何打印列表末尾没有逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文