java - 有没有更好的方法来使用 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+", ");
}
}
}
}
}
解决方案
只需更正您的逻辑,我只需检查要使用的顺序并使用动态增量进行一段时间循环:
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
当然,我至少会使用 aStringBuilder
而不是直接在控制台中打印。
推荐阅读
- c - 如何在 C 中写入文件和打印之间切换
- php - 如何从邮递员数组返回数组,如 [1,2,3]?
- python-3.x - 在 Python 3 中取消转义双反斜杠序列
- google-apps-script - 谷歌脚本不发送消息
- php - Laravel 8 我的播种数据有问题播种:调用未定义的方法 ::factory()
- signals - Kibana/Vega 中的地图和信号纬度、经度和缩放
- multithreading - Docker 与线程同时创建网络
- javascript - puppeteer 点击打开新标签并抓取所有图像
- r - 上面带有不变行的进度条(在 R 中)
- c - 在 Xcode Objective-C 项目中为 C 文件指定 Makefile