You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java for循环生成指定长度的1-10往复数字序列

代码问题修正方案

现有代码问题梳理

  • 变量名错误:接收用户输入的变量为number,但循环判断条件中误用了未定义的n4,会直接编译失败
  • 边界值输出逻辑不符合需求:按照规则到达10、1这两个边界时需要先重复输出一次边界值再切换方向,原有逻辑到达边界后直接修改值并切换方向,会丢失一次边界值输出,和示例不符

修正后完整代码

import java.util.Scanner;

public class SequenceGenerator {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Input number > ");
        int number = sc.nextInt();
        int j = 0;
        boolean ascending = true;
        // 用于处理末尾多余的逗号,也可按原有方式直接输出
        StringBuilder sb = new StringBuilder();
        
        for(int i = 1; i <= number; i++){
            if(ascending){
                if(j >= 10){
                    // 到达上边界,先输出当前10,仅切换方向不修改值
                    ascending = false;
                } else {
                    j++;
                }
            } else {
                if (j <= 1){
                    // 到达下边界,先输出当前1,仅切换方向不修改值
                    ascending = true;
                } else {
                    j--;
                }
            }
            if(i > 1) sb.append(", ");
            sb.append(j);
        }
        System.out.println(sb);
        sc.close();
    }
}

逻辑验证

输出结果和示例完全匹配:

  • 输入7,输出1, 2, 3, 4, 5, 6, 7
  • 输入12,输出1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9
  • 输入22,输出1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2

内容的提问来源于stack exchange,提问作者zaaph

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 22:15:08