Java递归实现凯撒密码返回异常输出的原因及可行性咨询
凯撒密码递归实现的问题解答
你的代码示例
import java.util.Scanner; public class test { public static String plainTxt; public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter the word you want to encrypt: "); String word1 = scan.next(); String word2 = scan.next(); String word3 = scan.next(); plainTxt = word1 + word2 + word3; Cipher cipher = new Cipher(); cipher.plainTxt1 = plainTxt; String cryptTxt = cipher.shifter(); System.out.println(cryptTxt.substring(0, word1.length()) + " " + cryptTxt.substring(word1.length(), word1.length() + word2.length()) + " " + cryptTxt.substring(word1.length() + word2.length(), plainTxt.length())); } } class Cipher { public String output; public int limit = 0; public char chr; public String plainTxt1; public Cipher() { limit = 0; } public String shifter() { if(plainTxt1.charAt(limit) == 'z' || plainTxt1.charAt(limit) == 'y') chr = (char)((int)plainTxt1.charAt(limit) - 23); else if(plainTxt1.charAt(limit) == 'x') chr = (char)((int)plainTxt1.charAt(limit) - 23); else chr = (char)((int)plainTxt1.charAt(limit) + 3); limit += 1; output += chr; if(limit == 11) return output; else shifter(); return output; } }
问题1:能不能用递归实现凯撒密码加密?
完全可以。递归实现的核心是明确两个要点:
- 终止条件:当所有输入字符处理完毕时停止递归
- 递归逻辑:每次递归只处理单个字符,完成右移3位的加密操作,再将结果拼接后进入下一层递归
你的需求是处理14字符,这个规模用递归完全没问题,不会出现栈溢出。不过递归并非最优解,循环实现会更直观高效,但用递归达成需求是完全可行的。
问题2:为什么返回结果带null,还只有前8个字符?
关于null的原因
Cipher类中的output是String类型的成员变量,Java中引用类型的默认值为null。第一次执行output += chr时,会自动把null转为字符串"null"再和字符拼接,所以结果开头会带上"null"。解决方法很简单,初始化时给output设为空字符串即可:public String output = "";
关于只输出前8个字符的原因
你的递归终止条件写的是limit == 11,但存在两个问题:
- 需求是处理14字符,正确的终止条件应该是
limit == plainTxt1.length(),这样所有字符处理完成后才返回 - 如果你实际输入的三个单词总长度为8,那么当
limit增长到8时,调用plainTxt1.charAt(limit)会触发数组越界异常,导致递归提前中断,最终只处理了前8个字符。另外你递归调用shifter()时没有接收返回值,但因为output是成员变量会逐步拼接,所以核心问题还是终止条件设置错误。
内容的提问来源于stack exchange,提问作者Kıvanç
相关产品推荐
相关产品推荐

