当我的程序打印出整数5到1
时,我需要帮助摆脱最后一个逗号int i;
for (i=10; i>1; --i){
if ( i%2==0) {
System.out.print( i/2 + "," );
打印出5,4,3,2,1,
我希望它打印出5,4,3,2,1
答案 0 :(得分:2)
一种有效的方法如下:
StringBuilder stringBuilder = new StringBuilder();
for (i=10; i>1; --i){
if ( i%2==0) {
stringBuilder.append(i/2);
stringBuilder.append(",");
}
}
stringBuilder.setLength(stringBuilder.length()-1);//remove last comma
System.out.println(stringBuilder.toString());
答案 1 :(得分:1)
一个简单的if会这样做,但更好,更有效方法是使用StringBuilder
int i = 0;
for (i = 10; i > 1; --i) {
if (i % 2 == 0) {
System.out.print(i / 2);
if (i > 2) {
System.out.print(",");
}
}
}
使用StringBuilder,代码将如下所示
public class Test {
public static void main(String[] args) {
int i = 0;
StringBuilder sb = new StringBuilder();
for (i = 10; i > 1; --i) {
if (i % 2 == 0) {
sb.append(i / 2).append(",");
}
}
sb.deleteCharAt(sb.length() - 1);
System.out.println(sb);
}}
答案 2 :(得分:0)
有几种不同的方式,例如写入缓冲区,在打印之前删除最后一个逗号,或者在if == 2 System.out.print(i / 2)时附加if条件;
答案 3 :(得分:0)
这是我使用StringBuilder类的通用解决方案:
/**
* @param x Inclusive from-value
* @param y Inclusive to-value
* @param step Gap between numbers
* @param separator What separates the numbers from each other?
* @return Numbers from x to y separated by a separator in String format
*/
public static String integersFromXToYWithSeparator(Integer x, Integer y,Integer step, Character separator) {
StringBuilder builder = new StringBuilder();
Integer localStep = Math.abs(step);
if (x < y) {
while (x <= y) {
builder.append(x);
builder.append(separator);
x+=localStep;
}
} else if (x > y) {
while (x >= y) {
builder.append(x);
builder.append(separator);
x-=localStep;
}
}
builder.setLength(builder.length()-1);
return builder.toString();
}
答案 4 :(得分:0)
由于java-8
有一个StringJoiner类,有助于解决此问题:
StringJoiner joiner = new StringJoiner(",");
for (int i = 10; i > 1; --i) {
if (i % 2 == 0) {
joiner.add(String.valueOf(i / 2));
}
}
System.out.println(joiner.toString());
或使用stream - api
String result =
IntStream.iterate(10, i -> i - 1)
.limit(10).filter(i -> i % 2 == 0)
.map(i -> i / 2)
.mapToObj(String::valueOf)
.collect(Collectors.joining(","));
System.out.println(result);