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
226 views
in Technique[技术] by (71.8m points)

java - Recursive function counts down 4->0, but then counts up 0>4, how can I stop the count up

The aim of this code is to confirm the letter A appears 4 times exactly but using a recursive function. I can get it to count correctly, but as soon as it begins to leave the recursive stacks, it then +1 instead of -1 (I think because it is leaving the stack).

Is there a better way to handle this, has me very stuck.

    public class App {
    public static boolean isPresentNTimes(String sequence, char marker, int count) {
        System.out.println("This is the count: " + count);
        if (sequence.isEmpty() != true){
            if(sequence.charAt(0) == marker) {
                isPresentNTimes(sequence.substring(1), marker, count-1);
                System.out.println("The count is" + count);
            }
            
            else {
                isPresentNTimes(sequence.substring(1), marker, count);
            }
        }
        
        if (count == 4){
            return true;
        } else {
            return false;
        }
    }

     public static void main(String []args){
        String seq1 = "ABBAACBA";
        System.out.println(isPresentNTimes(seq1, 'A', 4));
     }
}
question from:https://stackoverflow.com/questions/65928152/recursive-function-counts-down-4-0-but-then-counts-up-04-how-can-i-stop-the

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

1 Reply

0 votes
by (71.8m points)

This is what you actually want to implement:

public static boolean isPresentNTimes(String sequence, char marker, int count) {
    if(count < 0)
        return false;
    else if(count == 0 && sequence.isEmpty())
        return true;
    else if (!sequence.isEmpty()){
        if(sequence.charAt(0) == marker) {
            System.out.println("The count is " + count );
            count--;
        }
        return isPresentNTimes(sequence.substring(1), marker, count);
    }
    else
       return false;
}

Start with count=4 and decrement every time you found one element equals to mark. Make sure to add return before each recursive call (i.e., return isPresentNTimes (...)):

In your code you were comparing

  if (count == 4){
        return true;
    } else {
        return false;
    }

if count == 4, which does not make sense since you start already with count = 4.


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

...