我正在使用 for 循环打印一组整数,但我不希望最后一个数字后面有空格。我注意到 String 有类似 trim 的东西,但我找不到一个讨论循环中整数的类似 trim 方法的线程。
这是我的代码的一小段:
for(int i = 0; i < size.length; i++){
System.out.print("Enter the numbers you want in the array ");
size[i] = scanner.nextInt();
}
min = size[0]; // I had to initialize this after the program knew how big the array would be
for(int i = 0; i < size.length; i++){
System.out.print(size[i] + " ");
}
最佳答案
您可以将打印设置为有条件:
for(int i = 0; i < size.length; i++){
if(i == size.length -1){
System.out.print(size[i]);
} else {
System.out.print(size[i] + " ");
}
}
但是,我鼓励使用迭代器语法:
boolean first = true;
for(int val : size){
if(first){
System.out.print(val);
first = false;
} else {
System.out.print(" " + val);
}
}
关于java - java中是否有类似 "trim"的方法用于整数循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33061005/