基于START、STEP、END生成数字序列的Java代码求助
根据START、STEP、END生成数字序列的Java代码问题
我需要实现一个功能:根据输入的START、STEP、END值生成对应数字序列。比如输入START=5、STEP=2、END=13时,输出为5, 7, 9, 11, 13;输入START=5、STEP=3、END=20时,预期输出5 8 11 14 17 20。但我写的Java代码无法实现这个效果,我是Java新手,这是我的第一门编程语言,请求技术协助。
我的代码如下:
import java.util.Scanner; public class SeriesOfNumbers { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int [] numbers = {1 ,2 ,3 ,4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; int start = 0; int step = 0; int end = 0; boolean foundNum = false; System.out.print("START: "); start = scan.nextInt(); for(start = 0; start <= numbers.length; start++) { if(start == numbers.length) { foundNum = true; break; } } System.out.print("STEP: "); step = scan.nextInt(); for(step = 0; step <= numbers.length; step++) { if(start == numbers.length) { foundNum = true; break; } } System.out.print("END:"); end = scan.nextInt(); for(end = 0; end <= numbers.length; end++) { if(end == numbers.length) { foundNum = true; break; } } if(foundNum) { System.out.print("The output will be: "); } } }
预期输出示例:
START: 5 STEP: 3 END: 20 The output will be: 5 8 11 14 17 20
问题分析
你的代码存在几个关键错误:
- 冗余的
numbers数组:生成序列不需要预先定义固定范围的数组,完全可以通过计算直接生成。 - 输入值被覆盖:读取用户输入的START/STEP/END后,你用for循环重新给这些变量赋值,直接丢弃了用户输入的数值,导致后续逻辑完全失效。
- 缺失核心生成逻辑:代码里完全没有实现从START开始、按STEP递增到END的序列生成逻辑。
修正后的代码
import java.util.Scanner; public class SeriesOfNumbers { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // 获取用户输入 System.out.print("START: "); int start = scan.nextInt(); System.out.print("STEP: "); int step = scan.nextInt(); System.out.print("END: "); int end = scan.nextInt(); // 生成并输出序列 System.out.print("The output will be: "); int current = start; while (current <= end) { System.out.print(current); // 避免末尾输出多余空格 if (current + step <= end) { System.out.print(" "); } current += step; } scan.close(); } }
代码说明
- 输入读取:直接通过
Scanner获取用户输入的三个参数,不再做不必要的循环覆盖。 - 序列生成:使用
while循环从START出发,每次累加STEP,直到当前数值超过END时停止循环。 - 输出优化:判断当前数值加上STEP后是否仍小于等于END,以此决定是否输出空格,保证格式整洁。
测试示例输入后,输出完全符合预期:
START: 5 STEP: 3 END: 20 The output will be: 5 8 11 14 17 20
内容的提问来源于stack exchange,提问作者Abies
相关产品推荐
相关产品推荐

