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

Java编程:如何将L/R字符串转换为数组移动指令(-1/1)

解决方案

核心逻辑实现

你需要遍历输入的指令字符串,逐个解析每个字符对应的移动值,最后计算总偏移量并与初始位置相加得到最终位置:

  • 遍历字符串的每一个字符,判断是'L'还是'R'
  • 每遇到'L',总偏移量减1;遇到'R',总偏移量加1
  • 最终位置 = 初始位置 + 总偏移量

输入验证补充

结合你定义的范围限制,需要在代码中加入输入验证,避免非法数据:

  • 检查指令字符串长度是否在1-100之间
  • 检查初始位置是否在-10000到10000之间
  • 检查指令字符串是否仅包含L和R字符

修改后的完整代码

import java.util.Scanner;

public class Solution {
    public static void main(String args[] ) throws Exception {
        int maxCmdLength = 100;
        int minCmdLength = 1;
        int posMax = 10000;
        int posMin = -10000;
        
        String inputData;
        int initialPosition;
        Scanner input = new Scanner(System.in);
        
        // 获取指令字符串并验证
        System.out.println("Insert sequence of commands (L and R)");
        inputData = input.nextLine().trim();
        
        // 验证指令长度
        if (inputData.length() < minCmdLength || inputData.length() > maxCmdLength) {
            System.out.println("Error: Command sequence length must be between 1 and 100");
            return;
        }
        
        // 验证指令仅包含L和R
        for (char c : inputData.toCharArray()) {
            if (c != 'L' && c != 'R') {
                System.out.println("Error: Command sequence can only contain L and R");
                return;
            }
        }
        
        // 获取初始位置并验证
        System.out.println("Input starting position");
        initialPosition = input.nextInt();
        
        if (initialPosition < posMin || initialPosition > posMax) {
            System.out.println("Error: Starting position must be between -10000 and 10000");
            return;
        }
        
        // 计算总偏移量
        int totalOffset = 0;
        for (char c : inputData.toCharArray()) {
            if (c == 'L') {
                totalOffset -= 1;
            } else {
                totalOffset += 1;
            }
        }
        
        // 计算最终位置并输出
        int finalPosition = initialPosition + totalOffset;
        System.out.println("Final position: " + finalPosition);
        
        input.close();
    }
}

代码说明

  1. 输入验证:先检查指令的长度和合法性,再检查初始位置范围,确保输入符合要求
  2. 偏移量计算:通过toCharArray()遍历每个字符,根据字符类型累加偏移量,逻辑简单直接
  3. 结果输出:将初始位置与总偏移量相加,得到最终位置并打印

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:35:22