learning while and for loops
Hello!
My name is Jon and I am taking my first programming class in Java. I have to write a program that asks the user to enter a "new password." The program should check that the user's password has at least one uppercase letter, one lowercase letter, and one non-letter character. Furthermore, if the user enters an incorrect password, the program should keep asking for a new password until it gets a valid one. if the use enters an incorrect password 3 times, the program stops asking the user for a new password.
I'm sure there are 999 different ways to write this code. I'm really close with what I have, so I'm hoping I don't have to change everything around entirely. my code can correctly test whether the user's password is valid or not. i'm having trouble getting it to ask the user for a new pw if it is not valid the first time. Anyway, here's what I have so far! ^:)^
Code :
import java.util.*;
public class HWHelp
{
public static void main (String [] args)
{
boolean hasUpper = false;
boolean hasLower = false;
boolean hasNonLetter = false;
boolean passwordSet = false;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a new password. Make sure your password "
+ "contains at least one uppercase letter, one lowercase letter, "
+ "and at least one character that is either a numerical digit or other "
+ "non-letter.");
String usersPw = scan.next();
int j = 0;
while (!passwordSet && (j < 3))
{
for (int i = 0; i < usersPw.length(); i++)
{
while (i < usersPw.length())
{
char character = usersPw.charAt(i);
if (character >= 65 && character <= 90)
{
hasUpper = true;
}
if (character >= 97 && character <= 122)
{
hasLower = true;
}
if (character < 65 || (character > 90 && character < 97) || character > 122)
{
hasNonLetter = true;
}
i++;
}
}
if (hasUpper && hasLower && hasNonLetter)
{
passwordSet = true;
}
else
{
passwordSet = false;
}
j++;
}
if (passwordSet)
{
System.out.println("Password set.");
}
else
{
System.out.println("Password change aborted.");
}
}
}
Re: learning while and for loops
You have a loop that keeps going if the password is not set and is less than 3 attempts, so it probably makes sense to ask the user to enter the new password inside the loop. What do you think?
Re: learning while and for loops
Thank you! I figured it out! That was a big help.
JG