首页 > 解决方案 > 有没有更好的方法来使用 for 和 if-else 循环编写下面的程序?

问题描述

我已经为我的实践编写了以下代码,它运行良好,但我很好奇代码中使用的逻辑是否可以更有效地编写。欢迎任何见解:

public class RangeOfNumbers{
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.print("Start? ");
        int start = input.nextInt();
        System.out.print("End? ");
        int end = input.nextInt();
        if(start>=end){
            for (int i = start; i >=end; i--){
                if(i==end){
                    System.out.print(i);
                }else{
                    System.out.print(i+", ");
                }
            }
        }else{
            for (int i = start; i <=end; i++){
                if(i==end){
                    System.out.print(i);
                }else{
                    System.out.print(i+", ");
                }
            }
        }
    }
}

标签: javafor-loopif-statement

解决方案


只需更正您的逻辑,我只需检查要使用的顺序并使用动态增量进行一段时间循环:

public static void iterate(int start, int end) {
    int inc = (start < end) ? 1 : -1;

    end += inc; //Allow to include the value.

    do {
        System.out.print(start);

        start += inc;

        if(start != end){
            System.out.print(", ");
        }
    } while (start != end);
    System.out.println();
}

我已经用

10 -> 15

5、6、7、8、9、10

15 -> 10

15、14、13、12、11、10

这是Ideone中的完整比较

当然,我至少会使用 aStringBuilder而不是直接在控制台中打印。


推荐阅读