gpt4 book ai didi

java - java中是否有类似 "trim"的整数循环方法?

转载 作者:行者123 更新时间:2023-11-30 08:46:04 27 4
gpt4 key购买 nike

我正在使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com