我有以下Java程序,但我不想在最后一个元素之后分配“,”,怎么办?
String range = "400-450";
Integer startRange = null;
Integer endRange = null;
StringTokenizer st = new StringTokenizer(range,"-");
while(st.hasMoreTokens()) {
startRange = Integer.parseInt(st.nextToken());
endRange= Integer.parseInt(st.nextToken());
}
StringBuilder sb = new StringBuilder();
for (int i = startRange; i <= endRange; i++) {
sb.append(i).append(",");
}
System.out.println(sb);
输出应为
400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450
->最后没有逗号 最佳答案
就像
for (int i = startRange; i <= endRange; i++) {
sb.append(i);
if(i != endRange)
sb.append(",");
}