简体   繁体   English

递归字符串超出界限

[英]Recursion String out of Bounds

void two(int i)
{
    if(i<s.length());
    {
        char a=s.charAt(i);
        if(a==' ')
            a-=2;               
        a+=2;
        if((a<64||a>90)&&a!=32)
            a-=26;
        System.out.print(a);
        two(i+1);
    }
}

s is a global variable. s是全局变量。 When I execute, it gives my output correctly, but at the end it gives me the following error: 当我执行时,它正确地给出了我的输出,但是最后却给出了以下错误:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12

What is happening when the computer closes its workspaces in executing this recursive method? 当计算机在执行此递归方法时关闭其工作区时,会发生什么情况?

Remove the semicolon after the if statement, as it represents just an empty statement that's being executed once per a method called. if语句后删除分号,因为它只表示一个空语句,每个方法调用一次该语句即可。 This makes the remaining statements within the brackets not bound to the if statement and they are executed every time the method is called. 这使得括号内的其余语句不绑定到if语句,并且每次调用该方法时都将执行它们。

Since you increase the index i on each recursive call and the statements in the brackets are executed independently from the if , then you get an ArrayIndexOutOfBoundsException on char a=s.charAt(i); 由于您在每个递归调用上都增加了索引i ,并且括号中的语句与if无关地执行,因此您在char a=s.charAt(i);上获得了ArrayIndexOutOfBoundsException char a=s.charAt(i);

if(i<s.length());
                ↑

You should end up with something like: 您应该以如下形式结束:

if(i<s.length()) {
    char a=s.charAt(i);
    if(a==' ')
        a-=2;               
    a+=2;
    if((a<64||a>90)&&a!=32)
        a-=26;
    System.out.print(a);
    two(i+1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM