Zain Ul Abidin
Zain Ul Abidin

Reputation: 7

Return updated value of variable in java recursion

I want to verify whether a name contains special characters or not. Please let me know what's wrong with this code? My code is:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Name {
    static Scanner in = new Scanner(System.in);

    public static String verifyName() {
        System.out.print("Enter your name: ");
        String name = in.nextLine();
        Pattern p = Pattern.compile("[a-zA-Z0-9]*");
        Matcher m = p.matcher(name);
        if(!m.matches()) {
            System.out.println("Invalid Name");
            verifyName();
        }
        return name;
    }

    public static void main(String args[]) {
        String result = verifyName();
        System.out.print(result);
    }
}

Output:

Enter your name: @li
Invalid Name
Enter your name: #sd
Invalid Name
Enter your name: Zain
@li

Required Output:

Enter your name: @li
Invalid Name
Enter your name: #sd
Invalid Name
Enter your name: Zain
Zain

Thanks in advance!

Upvotes: 0

Views: 61

Answers (2)

Yılmaz edis
Yılmaz edis

Reputation: 163

Your whole code should be like

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Name {
    static Scanner in = new Scanner(System.in);

    public static String verifyName() {
        System.out.print("Enter your name: ");
        String name = in.nextLine();
        Pattern p = Pattern.compile("[a-zA-Z0-9]*");
        Matcher m = p.matcher(name);
        if (!m.matches()) {
            System.out.println("Invalid Name");
            return verifyName();
        }
        return name;
    }

    public static void main(String args[]) {
        String result = verifyName();
        System.out.print(result);
    }
}

For efficiency you may use iterative loop.

Upvotes: 1

Samuel
Samuel

Reputation: 1152

Your method needs to return the value of the name from the sub-function call

if(!m.matches()) {
    System.out.println("Invalid Name");
    return verifyName();
}

instead of

if(!m.matches()) {
    System.out.println("Invalid Name");
    verifyName();
}

however it may be better to use a loop instead of a recursive call:

public static String verifyName() {
    while (true)
    {
        System.out.print("Enter your name: ");
        String name = in.nextLine();
        Pattern p = Pattern.compile("[a-zA-Z0-9]*");
        Matcher m = p.matcher(name);
        if(m.matches()) {
           return name;
        }
    }

}

Upvotes: 0

Related Questions