enginear enginear - 1 month ago 6
Android Question

Can someone help me for convert this c# recursive function to java

I have a c# function and I want to translate my func to Java. But I'm making a mistake with this conversation and I cant figure it out. Here is my C# code:

public bool ParantezKontrol(string input, int numOpen = 0)
{
if (numOpen < 0)
return false;
if (string.IsNullOrEmpty(input))
return numOpen == 0;

char c = input[0];
string rest = input.Substring(1);
if (c == '(')
return ParantezKontrol(rest, numOpen + 1);
else if (c == ')')
return ParantezKontrol(rest, numOpen - 1);
else
return ParantezKontrol(rest, numOpen);
}


I couldnt realise
ParantezKontrol(string input, int numOpen = 0)
this definition and
return numOpen == 0;
this .

And here what i wrote Java code:

public boolean ParantezKontrol(String input, int numOpen){

if(numOpen<0) //numOpen=-1 olması durumunda parantez kapatılmayı unutmuştur. Bu durumda fonksiyon false değer gönderir.
return false;
if(input==null&&input.isEmpty()){

return true;
}
char c= input.charAt(0);

String rest = input.substring(1);

if(c == '(')
return ParantezKontrol(rest,numOpen+1); //Girilen metinde '(' varsa fonksiyonu sağdan çağır
else if (c==')')
return ParantezKontrol(rest,numOpen-1); // ')' varsa soldan çağır
else return ParantezKontrol(rest,numOpen);

}


can someone explain me where i'm making mistake and solve my problem please

Answer
public final boolean ParantezKontrol(String input)
{
    return ParantezKontrol(input, 0);
}

//Java does not support optional parameters. So you can overload this method
//ORIGINAL public bool ParantezKontrol(string input, int numOpen = 0)
public final boolean ParantezKontrol(String input, int numOpen)
{
        if (numOpen < 0)
        {
            return false;
        }
        if (isNullOrEmpty(input))
        {
            return numOpen == 0;
        }

        char c = input.charAt(0);
        String rest = input.substring(1);
        if (c == '(')
        {
            return ParantezKontrol(rest, numOpen + 1);
        }
        else if (c == ')')
        {
            return ParantezKontrol(rest, numOpen - 1);
        }
        else
        {
            return ParantezKontrol(rest, numOpen);
        }
}

isNullOrEmpty and substring methods are not present in Java, So Write your own methods:

public static boolean isNullOrEmpty(String string)
{
    return string == null || string.length() == 0;
}
public static String substring(String string, int start, int length)
{
    if (length < 0)
        throw new IndexOutOfBoundsException("Parameter length cannot be negative.");

    return string.substring(start, start + length);
}