Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

recursion - Getting the final else statement to run Java recursive method

Everything works in this class except for the final else statement. This is a recursive java letter tester. The program tests a user's word for all three letters (e, l, f). So far, Program throws exception error string index out of bounds if the word doesn't contain e, l and f

import java.util.Scanner;

public class FrettyRecursionMethod {

    static boolean e = false;
    static boolean f = false;
    static boolean l = false;
    static int n = 0;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String userWord;

        System.out.println("Enter a single word.");
        userWord = input.nextLine();

        elfish(userWord, 0);
    } // end main

    public static void elfish(String userWord, int n) {

        char ee = userWord.charAt(n);
            if (ee == 'e' || ee == 'E') {
            e = true;
        } // end if

            else if (ee == 'f' || ee == 'F') {
            f = true;
        } // end else if

            else if (ee == 'l' || ee == 'L') {
            l = true;
        } // end else if

        

        if (e == true && f == true && l == true) {
            System.out.println("Your word is elfish!");
        }

        else if (n < userWord.length()) {
            elfish(userWord, n + 1);
        }
        else
        {
            System.out.println("Your word isn't elfish.");
        } // end if-else else
    } // end elfish method

}// end class
question from:https://stackoverflow.com/questions/65876713/getting-the-final-else-statement-to-run-java-recursive-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm pretty sure it's because you don't terminate your recursion properly. In order to check the n+1 character, the current n has to be n-2 or the value of n+1 is going to be out of range. That's because charAt() is limited to at most n-1.

So you want to make sure that n is less than n-1 before you pass it.

else if (n < userWord.length()-1) {
        elfish(userWord, n + 1);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...