Problem Description:
Some Websites impose certain rules for passwords. Write a method that checks whether a string is a valid password. Suppose the password rule is as follows:
A password must have at least eight characters.
A password consists of only letters and digits.
A password must contain at least two digits.
Write a program that prompts the user to enter a password and displays "valid password" if the rule is followed or "invalid password" otherwise.
This is what I have so far:
import java.util.*;
import java.lang.String;
import java.lang.Character;
/**
* #author CD
* 12/2/2012
* This class will check your password to make sure it fits the minimum set requirements.
*/
public class CheckingPassword {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a Password: ");
String password = input.next();
if (isValid(password)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
public static boolean isValid(String password) {
//return true if and only if password:
//1. have at least eight characters.
//2. consists of only letters and digits.
//3. must contain at least two digits.
if (password.length() < 8) {
return false;
} else {
char c;
int count = 1;
for (int i = 0; i < password.length() - 1; i++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (Character.isDigit(c)) {
count++;
if (count < 2) {
return false;
}
}
}
}
return true;
}
}
When I run the program it only checks for the length of the password, I cannot figure out how to make sure it is checking for both letters and digits, and to have at least two digits in the password.
Suppose a valid password has:
8 or more characters, but not more than 16 characters
one or more uppercase characters
one or more lowercase characters
one or more digits
one or more special characters (like $, #, or !)
Code:
import java.util.Scanner;
public class Password {
public static void main(String[] args) {
// TODO Auto-generated method stub
int min =8;
int max=16;
int digit=0;
int special=0;
int upCount=0;
int loCount=0;
String password;
Scanner scan = new Scanner(System.in);
System.out.println(" Enter Your Password:");
password = scan.nextLine();
if(password.length()>=min&&password.length()<=max){
for(int i =0;i<password.length();i++){
char c = password.charAt(i);
if(Character.isUpperCase(c)){
upCount++;
}
if(Character.isLowerCase(c)){
loCount++;
}
if(Character.isDigit(c)){
digit++;
}
if(c>=33&&c<=46||c==64){
special++;
}
}
if(special>=1&&loCount>=1&&upCount>=1&&digit>=1){
System.out.println(" Password is good:");
}
}
if(password.length()<min){
for(int i =0;i<password.length();i++){
char c = password.charAt(i);
if(Character.isLowerCase(c)){
loCount++;
}
}
if(loCount>0){
System.out.println(" Password must be atleat "+min+" characters:");
System.out.println(" You need atleast one upper case chracter:");
System.out.println(" You need atleast one digit:");
System.out.println(" You need atleast one special chracter:");
}
}
else if(password.length()<min&&upCount>1){
for(int i =0;i<password.length();i++){
char c =password.charAt(i);
if(Character.isLowerCase(c)){
loCount++;
}
if(Character.isUpperCase(c)){
upCount++;
}
}
if(loCount>0&&upCount>0){
System.out.println(" Password must be atleast "+min+" chracters:");
System.out.println(" You need atleast one digit:");
System.out.println(" You need atleast one special chracter:");
}
}
if(password.length()>max||password.length()>=max&&upCount>1&&loCount>1&&digit>1){
System.out.println(" Password is too long.Limit is "+max+" chracters:");
System.out.println(" You need atleast one special chracter:");
}
if(password.length()>=min&&password.length()<=max&&loCount>0&&upCount>0&&digit>0&&special==0){
System.out.println(" You need atleast a special chracter");
}
if(password.length()>=min&&password.length()<=max&&loCount>0&&upCount>0&&digit==0&&special==0){
System.out.println(" You need atleast one digit:");
System.out.println(" You need atleast one special chracter:");
}
}
}
You almost got it. There are some errors though:
you're not iterating over all the chars of the password (i < password.length() - 1 is wrong)
you start with a digit count of 1 instead of 0
you make the check that the count of digits is at least 2 as soon as you meet the first digit, instead of checking it after you have scanned all the characters
As previously answered, you should chek all the password characters first. Count your digits and finally check if count is smaller than 2.
Here is the referring code.
if (password.length() < 8) {
return false;
} else {
char c;
int count = 0;
for (int i = 0; i < password.length(); i++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (Character.isDigit(c)) {
count++;
}
}
if (count < 2) {
return false;
}
}
return true;
}
public void run()
{
String password= readLine("Insert Password: ");
boolean len= true;
boolean letter= true;
boolean twodig= true;
if (password.length() < 8) {
len = false;
} else {
char c;
int count = 0;
for (int i = 0; i < password.length(); i++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
letter = false;
} else if (Character.isDigit(c)) {
count++;
}
}
if (count < 2) {
twodig = false;
}
}
if(len ==true && letter == true && twodig == true)
{
System.out.println("This password is valid ");
}
else
{
System.out.println("This password is invalid");
}
}
package Method;
/*
2. Write a Java method to check whether a string is a valid
password.
Password rules:
A password must have at least ten characters.
A password consists of only letters and digits.
A password must contain at least two digits.
Expected Output:
A password must have at least eight characters.
A password consists of only letters and digits.
A password must contain at least two digits
Input a password (You are agreeing to the above Terms and Conditions.): abcd1234
Password is valid: abcd1234
*/
public class CheckPassword {
public static String password;
public static int disitCounter = 0;
public static boolean isValid(String password) {
if (password.length() >= 10 ) {
for(int index = 0; index < password.length(); index++) {
char passChar = password.charAt(index);
if (!Character.isLetterOrDigit(passChar)) {
return false;
}
else {
if (Character.isDigit(passChar)) {
disitCounter++;
}
}
}
}
if(disitCounter < 2) {
return false;
}
return true;
}
public static void main(String[] args) {
password = "abcdefgh1w3";
if(isValid(password)) {
System.out.print("It is a valid password");
}
else {
System.out.print("It is a invalid password");
}
}
}
package com.parag;
/*
* #author Parag Satav
*/
public boolean check(String password) {
boolean flagUppercase = false;
boolean flagLowercase = false;
boolean flagDigit = false;
boolean flag = false;
if (password.length() >= 10) {
for (int i = 0; i < password.length(); i++) {
if (!Character.isLetterOrDigit(password.charAt(i))) {
return false;
}
if (Character.isDigit(password.charAt(i)) && !flagDigit) {
flagDigit = true;
}
if (Character.isUpperCase(password.charAt(i)) && !flagUppercase) {
flagUppercase = true;
}
if (Character.isLowerCase(password.charAt(i)) && !flagLowercase) {
flagLowercase = true;
}
}
}
if (flagDigit && flagUppercase && flagLowercase) {
flag = true;
System.out.println("Success..");
} else
System.out.println("Fail..");
return flag;
}
Related
How can I code this using subroutines in java with a loop so if they don't get it right it keeps repeating till they do. This is all i have so far. The user must enter a string that is greater than 6 characters long.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package containsmethod;
import java.util.*;
import java.lang.String;
import java.lang.Character;
import java.util.Scanner;
public class ContainsMethod {
public static boolean isValid(String password) {
if (password.length() < 6) {
return false;
} else {
char c;
for (int i = 0; i < password.length() -1; i ++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (Character.isDigit(c)) {
return false;
}
}
}
return false;
}
public static void main (String [] args) {
Scanner input = new Scanner (System.in);
{
System.out.print ("Please enter a string that is greater than 6 characters long. ");
String password = input.next();
if (isValid(password)) {
System.out.println ("That is a valid string onto stage 2.");
}
else
{
System.out.println ("That is a invalid string. Try again.");
}
}
First of all, your isValid function never returns true, even the case that user enters a password that is greater than 6 characters. So you should update your method like that:
public static boolean isValid(String password) {
if (password.length() < 6) {
return false;
} else {
char c;
for (int i = 0; i < password.length() - 1; i++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (Character.isDigit(c)) {
return false;
}
}
}
return true;
}
Then, you can take the user input in a do-while loop. So if the password is invalid it will keep asking. Here is your updated main method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
{
String password;
do {
System.out.print("Please enter a string that is greater than 6 characters long. ");
password = input.next();
if (isValid(password)) {
System.out.println("That is a valid string onto stage 2.");
} else {
System.out.println("That is a invalid string. Try again.");
}
}while (!isValid(password));
}
}
I've read that I would need to put "continue" after an "if" statement, but every I tried this with my if statement and it states that "continue cannot be used outside of a loop."
Set it in the loop. EX:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true){
System.out.print("Enter a password: The password must have at least eight characters, only letters and digits, and at least two digits. ");
String s = input.nextLine();
if (thepassword(s)) {
System.out.println("Valid Password");
break;
} else {
System.out.println("Invalid Password");
}
}
}
See more : Java Break and Continute
Use an outer infinite loop with a lable, then break the loop using break loop_lable. Check until a valid input is made.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a password: The password must have at least eight characters, only letters and digits, and at least two digits. ");
loop:for(;;)
{
String s = input.nextLine();
if (thepassword(s))
{
System.out.println("Valid Password");
break loop;
}
else
{
System.out.println("Invalid Password");
continue loop;
}
}
input.close();
}
public static boolean thepassword(String password) {
boolean thepassword = true;
if (password.length() < 8) {
thepassword = false;
} else {
int totaldigits = 0;
for (int n = 0; n < password.length(); n++) {
if (thedigit(password.charAt(n)) || theletter(password.charAt(n))) {
if (thedigit(password.charAt(n))) {
totaldigits++;
}
} else {
thepassword = false;
break;
}
}
if (totaldigits < 2) {
thepassword = false;
}
}
return thepassword;
}
public static boolean theletter(char c) {
return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}
public static boolean thedigit(char c) {
return (c >= '0' && c <= '9');
}
}
The main program should ask for a password that is 8 characters, 1 upper, 1 lower & 1 digit. Once passed requirements it should ask the user to re-enter the password and check that the two passwords match. I need help adding that section to my code. Currently, the code compiles with no problem.
import java.util.Scanner;
public class PassChecker2 {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
String inputPassword;
System.out.println(" Please enter your Password:");
inputPassword = input.next();
System.out.println(checkerPass(inputPassword));
System.out.println("");
//main(args);
}
public static boolean lenthgCk (String password) {
if (password.length() > 7) {
if(checkerPass(password)) {
return true;
}
}
else {
System.out.println("Password must be at least 8 characters long.");
return false;
}
return true;
}
public static boolean checkerPass (String password) {
boolean hasUpperCase = false;
boolean hasLowerCase = false;
boolean hasDigit = false;
char c;
for (int i = 0; i < password.length(); i++) {
c = password.charAt(i);
if(Character.isUpperCase(c)) {
hasUpperCase = true;
}
else if(Character.isLowerCase(c)) {
hasLowerCase = true;
}
else if(Character.isDigit(c)) {
hasDigit = true;
}
if(hasUpperCase && hasLowerCase && hasDigit) {
return true;
}
else {
System.out.println("Password is invalid must meet all requirements.");
return false;
}
}
return true;
}
}
Just input another string the same way you inputted the original password and check that they are both equal:
System.out.println(" Please confirm your Password:");
Stirng confirmPassword = input.next();
if (!confirmPassword.equals(inputPassword)) {
System.out.println("Passwords do not match");
// And possibly exit the program here?
}
import java.awt.Component;
import javax.swing.JOptionPane;
public class DoSomething {
public static void main(String[] args) {
String password = JOptionPane.showInputDialog(null,
"Please enter a password: ");
boolean number = false;
boolean character = false;
boolean symbol = false;
boolean length = false;
Component frame = null;
int counter = 0;
char [] letters = password.toCharArray();
for (char c: letters){
if(Character.isLetter(c)) {
if (password.matches("a-zA-Z")) {
counter++;
character= true;
}
}
if(Character.isLetterOrDigit(c)) {
counter++;
symbol = false;
}
if(Character.isDigit(c)) {
counter++;
if (counter >=2) {
number = true;
}
if (password.length()>=8) {
length = true;
}
if (character && length && number && !symbol){
JOptionPane.showMessageDialog("Your Password " +password +" is valid")
}
}
}
Edited -- it still hates length (even if it is 8 or more)
Why not just use regular expressions ?
public static boolean isValid(String password) {
return password.matches("([a-zA-Z]{8,})([0-9]{2,})");
}
This expression (if I'm not mistaken) checks if there are 8 or more characters(lowercase and uppercase) and if there are more than two numbers in the password. Symbols such as $, #, [space] will trigger the expression as false. EDIT: This regular expression only allows a password with 8 (or more) grouped characters and 2 (or more) numbers. Numbers cannot be separated (1MyPassword3) as this will flag the password as invalid. Further investigation will be required.
See the java API for regular expressions:
java 7 Pattern class
java 8 Pattern class
Also check out String.matches(String regex)
Reaction on comment
This code should suit you better then:
int letterCount = 0;
int numberCount = 0;
/*
* Loop through the password and count all the letters and characters
*/
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if (Character.toString(c).matches("[a-zA-Z]")) {
letterCount++;
}
if (Character.toString(c).matches("[0-9]")) {
numberCount++;
}
}
if (letterCount > 8) {
// password has 8 or more characters
}
if (numberCount > 2) {
// password has more than 2 numbers
}
Then if you really want to check length as well, you can add this piece of code (outside the for-loop)
if (password.length() >= 10) {
/* Since we need 2 numbers and 8 characters, the password
* can never be valid if it's smaller than 10 characters
*/
else {
/*
* Invalid password
*/
}
Assuming that your conditions for a valid password were:
At least 8 letters
At least 2 numbers
No symbols
At least 10 characters long
String password = JOptionPane.showInputDialog(null, "Please enter a password: ");
boolean number = false;
boolean character = false;
boolean symbol = false;
boolean length = false;
int letterCounter = 0;
int numCounter = 0;
Component frame = null;
char [] letters = password.toCharArray();
for (char c: letters){
if(Character.isLetter(c)) {
letterCounter++;
}
else if(Character.isDigit(c)) {
numCounter++;
}
else {
symbol = true;
}
}
//Checking booleans
if (password.length()>=10) {
length = true;
}
if (letterCounter>=8) {
character = true;
}
if (numCounter>=2) {
number = true;
}
if (character && length && number && !symbol){
JOptionPane.showMessageDialog(frame, "Your Password " + password + " is valid");
System.out.println("Success");
}
else {
System.out.println("Invalid");
}
What I am trying to do is put the # character before the domain. Im also trying to figure out how to put the domains to be the last 4 characters (example .com). How do I go about doing this? Any help would be appreciated.
I have listed my work on this link.
Code from the link:
import java.util.Scanner;
public class Username {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Must be between 8 and 20 characters.");
System.out.println("Must contain at least one uppercase and lowercase letter.");
System.out.println("Must contain at least one digit. ");
System.out.println("Must contain a special character ] [ ? / < ~ # ! $ % ^ & * ( ) + = } | : ; , > { ");
System.out.println("Must contain # before the domain");
System.out.println("The only acceptable domains are .com .edu .org .mil .gov .net");
System.out.println("\\n____Please enter your username to access the page. Follow the rules above.____ ");
String input = keyboard.nextLine();
while ((input.length() < 8) || (input.length() > 20))
{
System.out.println("Error! Your input is not valid.");
System.out.println("Please try again.");
keyboard.nextLine();
}
for (int i = 0; i <= input.length(); i++)
{
if(Character.isUpperCase(input.charAt(i)))
{
break;
}
else
{
if(i == input.length())
{
System.out.println("Error: Try again");
input = keyboard.nextLine();
}
}
}
for (int i = 0; i <= input.length(); i++)
{
if(Character.isLowerCase(input.charAt(i)))
{
break;
}
else
{
if(i == input.length())
{
System.out.println("Try again");
input = keyboard.nextLine();
}
}
}
char [] numbers= {\'0\',\'1\',\'2\',\'3\', \'4\',\'5\',\'6\',\'7\',\'8\',\'9\'};
char[] inputArray = input.toCharArray();
for (int i = 0; i < inputArray.length; i++)
{
for (int j = 0; j < numbers.length; j++)
{
if (inputArray[i]== numbers[j])
{
i=inputArray.length;
j=numbers.length;
}
else
{
if(i == inputArray.length-1 && j== numbers.length-1)
{
System.out.println("Try again");
input = keyboard.nextLine();
}
}
}
char [] SpecialCharacter = {\']\',\'[\',\'?\',\'/\',\'<\',\'~\',\'#\',\'.\',\'!\',\'$\',\'%\',\'^\',\'&\',\'*\',\'(\',\')\',\'+\',\'=\',\'}\',\'|\',\'>\',\'{\' };
char[] inputArray2 = input.toCharArray();
for (int k = 0; k < inputArray2.length; k++)
{
for (int l = 0; l < SpecialCharacter.length; l++)
{
if (inputArray2[k]== SpecialCharacter[l])
{
k=inputArray2.length;
l=SpecialCharacter.length;
}
else
{
if(k == inputArray2.length-1 && l == SpecialCharacter.length-1)
{
System.out.println("No...Try Again");
input = keyboard.nextLine();
}
}
}
String domain1 = ".com";
String domain2 = ".edu";
String domain3 = ".org";
String domain4 = ".mil";
String domain5 = ".gov";
String domain6 = ".net";
}
}
}
}
if you only need to verify that the user has entered a valid email or not then you should use regular expersion for that it makes it more easy and fast.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidator {
private Pattern pattern;
private Matcher matcher;
private static final String EMAIL_PATTERN =
"^(?=.*[0-9]*[a-z]*[A-Z])(?=.*[a-zA-Z])([a-zA-Z0-9]{8,20}+#[A-Za-z0-9]+.(com|org|edu|mil|net))$";
public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}
/**
* Validate hex with regular expression
*
* #param hex
* hex for validation
* #return true valid hex, false invalid hex
*/
public boolean validate(final String hex) {
matcher = pattern.matcher(hex);
return matcher.matches();
}
}
hope this will help you. =)
i'll just put this here...
Insert the parts of your code where needed.
import java.util.Scanner;
public class Username {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Must be between 8 and 20 characters.");
System.out.println("Must contain at least one uppercase and lowercase letter.");
System.out.println("Must contain at least one digit. ");
System.out.println("Must contain a special character ] [ ? / < ~ # ! $ % ^ & * ( ) + = } | : ; , > { ");
System.out.println("Must contain # before the domain");
System.out.println("The only acceptable domains are .com .edu .org .mil .gov .net");
System.out.println("\\n____Please enter your username to access the page. Follow the rules above.____ ");
boolean isOK = false;
String input=new String();
while(!isOK){
input=keyboard.nextLine();
if(input.length() < 20 || input.length() > 8) //length check
{
isOK=true;
}
else
{
isOK=false;
continue;
}
if(input.contains('#')) //check domain
{
isOK=true;
}
else
{
isOK=false;
System.out.println("No # before domain!");
continue;
}
String[] tokens = input.split("#");
String domain=tokens[1];
String username=tokens[0];
//check if contains digit
...
//check uppercase and lowercase in username
...
//check special character in username
...
//split domain
tokens = domain.split(".");
String domainEnding = tokens[1];
//check if the input domain endings are allowed
...
}
}
}
So where the part of input is wrong just use isOK=false;
continue;
BTW: why are you using \' in special character and number arrays?
You could use just '1' , '#' etc.