string - I have java code for entering a password following certain rules -
some websites impose rules passwords. writing method checks whether string valid password.
the rules of password are:
- a password must have @ least 8 characters
- a password consists of letters , digits
- a password must contain @ least 2 digits
i figured out of code, think got concept correct right no matter password enter prints out "invalid password"..i tried running debugger got confused.
this code below:
import java.util.scanner; public class practice { public static void main(string[] args) { system.out.print("enter password"); scanner input = new scanner(system.in); string password = input.nextline(); boolean iscorrect = checkpassword(password); if(iscorrect) { system.out.println("valid password"); } else { system.out.println("invalid password"); } } //this method checks password public static boolean checkpassword(string password) { int countdigit = 0; if (password.length() >=8 ){ return false; } for(int = 0; <password.length(); i++) { if(!(character.isletterordigit(password.charat(i)))) { return false; } } for(int = 0; i<password.length(); i++){ if((character.isdigit(password.charat(i)))){ countdigit = countdigit + 1; } } if (countdigit >= 2){ return true; } else return false; } }
the error here:
if (password.length() >=8 ){ return false; }
here if password longer or equal 8 characters, password invalid, complete opposite of requirement. change to:
if (password.length() < 8 ){ return false; }
also, can reduce number of loops make code faster. can count number of digits , check isletterordigit
in same loop:
int countdigit = 0; if (password.length() < 8) { return false; } (int = 0; < password.length(); i++) { if (!(character.isletterordigit(password.charat(i)))) { return false; } if ((character.isdigit(password.charat(i)))) { countdigit = countdigit + 1; } } if (countdigit >= 2) { return true; } else { return false; }
Comments
Post a Comment