Java - 从 for 循环输出数字时如何去掉最后一个逗号

标签 java

因此,当用户输入数字时,我正在运行一个程序,然后打印出该整数之前的奇数。

public class odd2 {

static Scanner UI = new Scanner(System.in);

public static void main(String[] args) {
    {
        // TODO Auto-generated method stub
        System.out.print ( " Please enter a number ");

        if (UI.hasNextInt() )
        {
            int numberEntered = UI.nextInt();
        //define the limit


        System.out.println("Printing Odd numbers between 1 and " + numberEntered);

        for(int i=1; i < numberEntered; i++){

                //if the number is not divisible by 2 then it is odd
                if( i % 2 != 0){
                        System.out.print(i + ",");
                }
        }

目前,它会打印出所有数字,并在其后添加逗号。有什么办法可以跳过 ,.我的一个解决方案可能可以创建这些整数的数组,然后使用 stringToArray 但我想知道是否有更简单的东西我丢失了。

最佳答案

像这样的东西会起作用:

System.out.print( (i == numberEntered - 1 || i == numberEntered - 2) ? i : i + ",");

使用三元运算符检查“i”是否是最终值,然后仅打印数字。

关于Java - 从 for 循环输出数字时如何去掉最后一个逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40104595/

相关文章:

java - Citrus 框架 - 尝试在 JSON 中使用 validator 会导致 header ACCEPT 出现错误

java - 异常: Operation not allowed after ResultSet closed while fetching value from two table

java - Glassfish-3.0.1 混合用户 session - SSO

java - Spring jpa存储库查找全部

尽管使用 CLASSPATH 环境变量,但仍出现 java.lang.ClassNotFoundException

java - 如何使用 JAXB Marshaller 编码 java.lang.Exception?

java - 验证 java 版本兼容性

java - 如何为选定行着色 TableViewer Java

java - 强制浏览器在单独的窗口中打开我的小程序

java - 如何在 Jolt Transformation 中循环时展平对象数组?