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

标签 java loops trim removing-whitespace

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

相关文章:

c++ - 如何将输入的数字字符串转换为 int 数组?

java - Hibernate 投影属性整个对象

java - 在 Cucumber java 的特定步骤中访问 Cucumber 中的场景对象

c - 嵌套 for/while 循环和数组,过滤掉数组中的数字

javascript - 循环和函数

Linux:如何批量重命名文件,修剪文件名中间和结尾的字符

PHP 数组修剪空白索引值

sql - 修剪完整的字符串,而不是字符 - Redshift

java - 将消息从服​​务器传递到 html (GUI) 的最佳方式是什么

java - 将 JDateChooser 与数据库一起使用时出现问题