java - Find if Entered Password is valid or not? -
this interview question. think code below, works bit , has errors. problem follows -
in 1-9 keypad 1 key not working. if 1 enters password not working key not entered. have given expected password , entered password. check entered password valid or not ex: entered 164, expected 18684 (you need take care when u enter 18684 , 164 both taken 164 input)
the code above below.
public static void main(string[] args){ system.out.println(isamatch("164","18684")); } static boolean isamatch(string actual, string expected) { char faultykey = '\0'; int = 0, j = 0; for(; < expected.length() && j < actual.length(); ++i) { if(actual.charat(j) != expected.charat(i)) { if('\0' != faultykey){ if(faultykey != expected.charat(i)) return false; } else{ faultykey = expected.charat(i); } } else{ ++j; } } system.out.println("faultykey= "+faultykey); return (i == expected.length() - 1 && j == actual.length() - 1)? true : false; }
it detecting faulty key correctly (ex here 8), giving wrong output (as false) though test case used above should give true. suggestions fix this? if better method/ideas appreciated.
static boolean isamatch(string actual, string expected) { char faultykey = '\0'; int = 0, j = 0; (; < expected.length(); ++i) { if (j >= actual.length() || actual.charat(j) != expected.charat(i)) { if ('\0' != faultykey) { if (faultykey != expected.charat(i)) { return false; } } else { faultykey = expected.charat(i); } } else { ++j; } } system.out.println("faultykey= " + faultykey); return (i == expected.length() && j == actual.length()) ? true : false; }
consider following condition
system.out.println(isamatch("164", "186848"));
your logic not work, because before meets length j meet actual length. dont need have condition j < actual.length
in loop.
Comments
Post a Comment