iVvaibhav
iVvaibhav

Reputation: 105

My code is printing only false. What can be wrong?

I am getting output as false, everytime.

My aim is to print true, if String t is present in the same order in String s.

For example:

  1. String s = "gagbgcgd";
    String t = "abcd";
    

    Expected output:

    true

  2. String s = "gagcgdgb";
    String t = "abcd";
    

    Expected output:

    false

Here is the code.

public class StringCompare {
    public static boolean stringCompare(String t,String s) {
        if (t.length() == 0) {
            return true;
        }
        if (s.length() == 0) {
            return false;
        }
        if (t.charAt(0) == s.charAt(0)) {
            stringCompare(t.substring(1), s.substring(1));
        }
        else {
            stringCompare(t, s.substring(1));
        }
        return false;
    }

    public static void main(String[] args) {
        String s = "acaoadaianaga";
        String t = "coding";
        System.out.println(stringCompare(t,s));
    }
}

Upvotes: 1

Views: 118

Answers (4)

Long Vu
Long Vu

Reputation: 131

The main problem of your code is in the first execution of the recursion always return false no matter what the return value of remaining execution in the recursion.

You should change your code to something like:

if(t.charAt(0)==s.charAt(0)){
    return stringCompare(t.substring(1), s.substring(1));
}
else{
    return stringCompare(t,s.substring(1));
}

and remove the last return false; statement.

Upvotes: 2

Carlos Gutierrez
Carlos Gutierrez

Reputation: 1

You should use .contains. Example:

 boolean istrue = t.contains(s);

Upvotes: -2

Joe
Joe

Reputation: 410

This is because the outer recursive calls you always returns false except if(t.length()==0){return true;}

look at Elliott Frisch's answer.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

When you recurse, you don't return the result of the recursion. Change

if(t.charAt(0)==s.charAt(0)){
    stringCompare(t.substring(1), s.substring(1));
}
else{
    stringCompare(t, s.substring(1));
}

to something like

if(t.charAt(0)==s.charAt(0)){
    return stringCompare(t.substring(1), s.substring(1));
}
else{
    return stringCompare(t, s.substring(1));
}

Upvotes: 11

Related Questions