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:

  1. a password must have @ least 8 characters
  2. a password consists of letters , digits
  3. 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

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -