java - Using Recursion with Username matching -
this question has answer here:
- how compare strings in java? 23 answers
i implementing string matching algorithm username database. method takes existing username database , new username person wants , checks see if username taken. if taken method supposed return username number isn't taken in database.
example:
"justin","justin1", "justin2", "justin3"
enter "justin"
return: "justin4" since justin , justin numbers 1 thru 3 taken.
in code sample below, newmember
returns justin1 though exists--where mistake?
public class username { static int j = 0; static string newmember(string[] existingnames, string newname){ boolean match = false; for(int = 0; < existingnames.length; i++){ if(existingnames[i] == (newname)){ match = true; } } if(match){ j++; return newmember(existingnames, newname + j); } else{ return newname; } } public static void main(string[] args){ string[] usernames = new string[9]; usernames[0] = "justin1"; usernames[1] = "justin2"; usernames[2] = "justin3"; usernames[3] = "justin"; system.out.println(newmember(usernames, "justin")); // don't understand why returns justin1 when name taken // in array. } }
this line:
if(existingnames[i] == (newname)){
should become
if(existingnames[i].equals(newname)){
in general, use equals
instead of ==
strings in java.
Comments
Post a Comment