消除最后的逗号&空间 [英] Eliminating Last Comma & Space
本文介绍了消除最后的逗号&空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是原始提示:
编写for循环以打印数组hourlyTemp的所有NUM_VALS个元素。使用逗号和空格分隔元素。例如:如果hourlyTemp = {90,92,94,95},print:
90,92,94,95
"Write a for loop to print all NUM_VALS elements of array hourlyTemp. Separate elements with a comma and space. Ex: If hourlyTemp = {90, 92, 94, 95}, print: 90, 92, 94, 95
请注意,最后一个元素后面没有逗号,空格或换行符。
Note that the last element is not followed by a comma, space, or newline."
这是我的代码:
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 = 0;
hourlyTemp[0] = 90;
hourlyTemp[1] = 92;
hourlyTemp[2] = 94;
hourlyTemp[3] = 95;
for (i = 0; i < NUM_VALS; i++) {
System.out.print(hourlyTemp[i] + ", ");
}
System.out.println("");
return;
}
}
我的输出是90,92,94,95 ,什么时候应该是90,92,94,95
My output is "90, 92, 94, 95, " when it should be "90, 92, 94, 95"
如何消除最后一个逗号和空格?
How do i eliminate the last comma and space?
推荐答案
检查是否达到了最后一次迭代。如果不打印逗号,否则不要。
Check if the last iteration is reached. If not print the comma, otherwise don't.
替换:
for (i = 0; i < NUM_VALS; i++) {
System.out.print(hourlyTemp[i] + ", ");
}
使用:
for (i = 0; i < NUM_VALS; i++) {
if (i == (NUM_VALS - 1)) System.out.print(hourlyTemp[i]);
else System.out.print(hourlyTemp[i] + ", ");
}
这篇关于消除最后的逗号&空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文