You need to enable JavaScript to run this app. Java新手求助:扩展ROT13代码实现带格式保留的段落加密
优惠活动
大模型
产品
解决方案
定价
更多

Java新手求助:扩展ROT13代码实现带格式保留的段落加密

现有代码的问题定位
  • 缺少字符类型判断,仅能适配全小写的连续单词场景:原逻辑直接用小写字母的计算规则处理每个字符,碰到大写字母、标点、空格、换行符时会运算出错误字符,完全无法保留原有段落格式
  • 输入逻辑仅支持读取单行文本,无法适配带换行的多段落输入
段落级ROT13的实现方案
  • 逐字符遍历完整段输入,按字符类型做分支处理:
    • 小写英文字母:按字母表偏移13位、模26循环的规则转换
    • 大写英文字母:以大写字母表为基准,执行和小写一致的偏移转换
    • 其余所有字符(标点、空格、换行、数字、特殊符号):直接保留原字符,不做改动,完整还原原段落排版
  • 长文本拼接使用StringBuilder优化性能,避免生成大量临时字符串对象
可直接运行的修正代码
import java.util.Scanner;

public class Assignment1b {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Please paste your paragraph: ");
        // 调整读取分隔符,支持读取包含换行的完整段落
        s.useDelimiter("\\Z");
        String paragraph = s.next();
        StringBuilder rot13Result = new StringBuilder();
        
        for(int i = 0; i < paragraph.length(); i++){
            char currentChar = paragraph.charAt(i);
            // 转换小写字母
            if(currentChar >= 'a' && currentChar <= 'z'){
                int offset = currentChar - 'a';
                offset = (offset + 13) % 26;
                rot13Result.append((char)(offset + 'a'));
            // 转换大写字母
            } else if(currentChar >= 'A' && currentChar <= 'Z'){
                int offset = currentChar - 'A';
                offset = (offset + 13) % 26;
                rot13Result.append((char)(offset + 'A'));
            // 非字母字符直接保留
            } else {
                rot13Result.append(currentChar);
            }
        }
        System.out.println("\nROT13 encrypted result: \n" + rot13Result);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.03 09:24:04