Java code Check Password for Letter and Digit? - java

The first post was confusamagin. My assignment is to create a password prompt program. The password needs to be checked to see if it does have at least one digit and one letter in it. Also the password length must be between 6 - 10.
My problem is trying to figure out how see if a digit and letter exist the password. In the check password area I am not sure where to begin really. I am not sure how to see if it has a Letter and a Digit in one. I know how to do either or by using a for statement to count and check but all it does is check to see rather it contains all letters or all digits.
import java.util.Scanner;
class Password {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//------ENTER A USERNAME
System.out.println("Welcome please enter your username and password.");
System.out.print("Username >>");
input.nextLine();
//------PASSWORD AUTHENTICATION BEGIN
String password = enterPassword();
while ( !checkPassword(password) ) {
System.out.println("Password must be 6 - 10 characters long!");
password = enterPassword();
}
//------PASSWORD VERIFY
String passwordverify = enterPassword();
while (!password.equals(passwordverify)){
System.out.println("ERROR - Passwords DO NOT MATCH Re-Enter Passwords Again");
password = enterPassword();
}
//------ACCEPT PASSWORD
System.out.println("Username and Password Accepted!");
}
//--ENTER PASSWORD STATEMENT
public static String enterPassword(){
String password;
Scanner input = new Scanner(System.in);
System.out.print("Password >>");
password = input.nextLine();
return password;
}
//--BOOLEAN CHECK PW
public static boolean checkPassword(String password){
int length;
length = password.length();
if (length < 6 || length > 11){
return false;
}
for (int i = 0; i < password.length();i++){
if (!Character.isLetter(password.charAt(i)))
return false;
}
return true;
}
}

Without writing your homework assignment.... you're on the right track you have make sure that your count of letters, and your count of numbers are both at least 1.

Your code is only missing variable counters. Keep two counters: one to count letters, one to count numbers, and perform the if test at the end of both for loops inside checkPassword to check if both counters are at least one.
An alternative of doing this is using regular expression. See this link:
http://www.mkyong.com/regular-expressions/how-to-validate-password-with-regular-expression/

Related

Strings || Case Sensitive

Need to make a password program, where the user sets a password at the beginning and the password can be entered 3 times before the program is stopped. The program can not be case sensitive.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int attempts = 3;
String password = "";
System.out.println("Please input your password.");
Scanner stringScanner = new Scanner(System.in);
String PASSWORD = stringScanner.next();
while (attempts-- > 0 && !PASSWORD.equals(password)) //compares and then decrements
{
System.out.print("Enter your password: ");
password = sc.nextLine();
if (password.equals(PASSWORD))
System.out.println("Access Granted");
else
System.out.println("Incorrect. Number of attempts remaining: " + attempts);
}
if (attempts < 1) {
System.out.println("You have entered too many incorrect passwords, please try again later.");
}
else {
System.out.println("Secret: Water is not Wet.");
}
}
}
Program prints as expected, but is not case sensitive
The first part of your question says The program can not be case sensitive while afterwards you are stating that Program prints as expected, but is not case sensitive, so it's a little difficult to understand what you want. But by looking at the code and seeing that it is doing a case-sensitive comparison, and that you are not happy with it's behavior, I'm guessing you want this to be a case-INsensitive comparison.
In that case, you can use String#equalsIgnoreCase: !PASSWORD.equalsIgnoresCase(password)
simply if you need not to consider the case sensitive just do password.equalIgnoreCase(PASSWORD)
but if you need to be sure that both have same case sensitive you can just convert both variables to .toUpperCase before the comparison

Prompt the user to enter a password which matches a specific pattern

I have written some code but I cant seem to figure out how to get the exact number of characters, numbers, or symbols. I fixed my code a bit but it does not work and I'm not sure why.
My requirements are
Write a Java program that prompts the user to enter a password that matches a specific pattern. Your program must approve the user's entry.. Here is the pattern, in this order:
-1 or more upper case letters
-two lower case letters
-1 or 2 digits
-zero or 1 upper case letters
-any two of this group ##$%^&
My Code:
import java.util.Scanner;
public class TestingCenter {
public static void main(String[] args) {
int digit=0;
int special=0;
int upCount=0;
int upCount2=0;
int loCount=0;
String password;
Scanner scan = new Scanner(System.in);
System.out.println(" Enter Your Password:");
password = scan.nextLine();
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(Character.isUpperCase(c)){
upCount2++;
}
if(c>=33&&c<=46||c==64){
special++;
}
}
if(special==2&&loCount==2&&upCount>=1&&(digit==1||digit==2)&&upCount2<=1){
System.out.println(" Password is good:");
}
}
}
If I understand correctly, in this order literally means in that given order.
If that's the case, you want regex. Forget counting characters.
1 or more upper case letters [A-Z]+
two lower case letters [a-z]{2}
1 or 2 digits \d{1,2}
zero or 1 upper case letters [A-Z]?
any two of this group ##$%^& [##$%^&]{2}
So,
Scanner scan = new Scanner(System.in);
System.out.println(" Enter Your Password:");
String password = scan.nextLine();
System.out.println(password.matches("[A-Z]+[a-z]{2}\\d{1,2}[A-Z]?[##$%^&]{2}");
If that's not what your instructions meant, then check out your conditionals. Clearly not everything should be >= 1

Repeating error message inside a while loop [duplicate]

This question already has answers here:
Loop user input until conditions met
(3 answers)
Closed 7 years ago.
I'm currently working my way through a Udemy Java course and am practicing what i have learnt thus far.
I have the following simple program which i am planning on using to get the user to input his name.
import java.util.Scanner;
public class Adventure {
public static final int menuStars = 65;
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String firstName = "";
String lastName = "";
boolean validName = false;
while(!validName){
//Entering first name
System.out.println("Please enter your first name.");
try {
firstName = input.nextLine();
if(firstName.length() == 0){
throw new Exception("Please enter a first name of at least 1 character.");
}else{
//Entering last name
System.out.println("Please enter your last name.");
lastName = input.nextLine();
if(lastName.length() == 0){
throw new Exception("Please enter a last name of at least 1 character");
}else{
System.out.println("You have entered " + firstName +" " + lastName);
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
continue;
}
//Used to terminate loop when both first & last names are valid
validName = true;
}
}
}
I want to make the program repeat the error message when the user inputs a blank name instead of restarting the entire program from the beginning.
E.g When the user enters a blank first name, i want the program to keep repeating "Please enter a first name of at least 1 character" and when the user enters a blank last name, for it to keep repeating "Please enter a last name of at least 1 character" until the user enters a valid name.
However, currently when the user enters a blank first name or last name, my program will repeat itself from the very beginning instead of repeating just the error message.
How would i go about making the program repeat just the error message?
Use a boolean variable that stores true when "Please enter your first name." is printed. Check before printing this string each time if this variable is false or not. Also, initialize it to false before the loop. Same idea goes for last name.
if(!printed)
{
System.out.println("Please enter your first name.");
printed=true;
}
havent tested that but i am guessing it can be like that, with out try/catch though, it just makes no sense to me using it in the way you have it on your code
String firstName = "";
String lastName = "";
System.out.println("Please enter your first name.");
firstName = input.nextLine();
while(firstName.length<1){
System.out.println("Please enter a first name of at least 1 character.");
firstName = input.nextLine();
}
lastName=input.nextLine();
while(firstName.length<1){
System.out.println("Please enter a last name of at least 1 character.");
lastName = input.nextLine();
}
System.out.println("You have entered " + firstName +" " + lastName);
Edit, some basic info about exceptions
try catch is used when something unexpected happens and you try to find a way round it. for example if an array of 10 positions is expected at some point and a smaller array (lets say 4 positions) is being used. Then this would cause an exception causing the program to terminate with no further information.
With try catch you can check what the problem is, and try to either inform the user to do something(if they can) or close the program in a better way, using System.exit() for example and saving all the work that was done till that point
An other example is that if you ask for 2 numbers to do an addition. if the user enters letters instead of number the int sum=numbA+numbB; would throw and exception. This of course could be handled using an if. but even better would be something like this
A whitespace is actually considered a character, so the check of (length == 0) doesn't work for your purposes.
Although the following code below is incomplete (ex: handles the potentially undesirable case of firstname=" foo", (see function .contains()), it does what the original post asks - when the user enters a blank first/last name, it keeps repeating "Please enter a first/last name of at least 1 character" until the user enters a valid first/last name.
import java.util.Scanner;
public class Adventure {
public static final int menuStars = 65;
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String firstName = "";
String lastName = "";
boolean firstNameLegal = false;
boolean lastNameLegal = false;
// Entering first name
while (!firstNameLegal) {
System.out.println("Please enter your first name.");
firstName = input.nextLine();
if (!firstName.equals(" "))
firstNameLegal = true;
else
System.out.println("Please enter a first name of at least 1 character.");
}
// Entering last name
while(!lastNameLegal){
System.out.println("Please enter your last name.");
lastName = input.nextLine();
if(!lastName.equals(" "))
lastNameLegal = true;
else
System.out.println("Please enter a last name of at least 1 character.");
}
System.out.println("You have entered " + firstName +" " + lastName);
}
}

Write a program reads in a series of passwords into an array&Store 10 passwords.After, have the reader enter a password & see if it is in the array.

import java.util.Scanner;
public class Password
{
public static void main (String [] args)
{
{String [] myArray = new String[10];
int i;
System.out.println("Enter a password: ");
Scanner in = new Scanner(System.in);
String myString = in.next();
//my arrays are here//
myArray[0] = "password";
myArray[1] = "password1";
myArray[2] = "iloveyou";
myArray[3] = "abc123";
myArray[4] = "abc1234";
myArray[5] = "bears55";
myArray[6] = "shelby27";
myArray[7] = "Mjcheer38";
myArray[8] = "sillypineapple";
myArray[9] = "freshvase";
//not sure if this is where this for loop should go//
for (i=0;i<9;i++)
{
if (myString.equals(myArray[i]))
{
System.out.println("Password Accepted");
break;
}
else
{
System.out.println("Password Rejected");
break;
}
//I think my if statements are right....//
}
}
}
}
The full question is: 6. Write a program reads in a series of passwords into an array. Store 10 passwords. After creating the password array, have the reader enter a password and see if it is in the array. If it is there, print “Valid password” and if it is not there, print “Invalid password”. I have no idea what I could be doing wrong. For the first password, it says accepted, but for the rest it says rejected. Can someone please point out where I have gone wrong. I cannot seem to figure it out.
Well, you don't want to immediately break out of the loop; that defeats the purpose of the loop entirely.
Including a break; statement in every possible execution branch of the for loop (i.e. it's impossible for break; not to execute) will ensure that the loop body will never execute multiple times. It won't be much of a loop, then.
Try turning your for loop into this:
boolean validPassword = true;
for (i=0;i<9;i++) {
if (myString.equals(myArray[i])) {
System.out.println("Invalid password");
validPassword = false;
break;
}
}
if(validPassword) {
System.out.println("Valid password");
}
Note that you only want to print "Valid password" if the user-entered string is not equal to ANY of the passwords in the array. Thus, printing "Valid password" and then "Invalid password" wouldn't be a good idea.

I need help writing a program that determines if a password is valid or not

The program allows the user to enter a string representing a password and determines whether or not it is valid. The password must be 8 characters long, include one lower case letter, one upper case letter, a number, and a symbol (ex. !##).
The output should read:
Entered Password: (whatever the user entered)
Verdict: (either valid or invalid)
Here is my code so far:
import java.util.*;
public class PasswordTest
{
public static void main(String[]args)
{
Scanner input = new Scanner (System.in);
System.out.print("Enter a password: ");
String Pass = input.next();
System.out.println("Entered Password: " + Pass);
if (Pass.length() < 8)
{
System.out.println ("Verdict: Invalid");
}
if (Pass.length() >= 8)
{
System.out.println ("Verdict: Valid");
{
}
}
I'm not certain how to go about this. I'm assuming I'll need a loop statement to determine whether or not it contains a capital and lowercase letter as well as a number and symbol.
No need for loops, use || and && operators instead, that way only 1 if statement is needed.
You can use regex:
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\S+$).{8,}$
Implementation:
import java.util.regex.*;
public class passwordvalidation {
public static void main(String[] args) {
String passwd = "aaZZa44#";
String pattern = "(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{5,10}";
System.out.println(passwd.matches(pattern));
}
}
Find more here in this stackoverflow post: Regex explained

Categories