I want to create an application that asks the user to enter password from input dialogs.The password must be less than 10 characters and more than 6 characters.Also,the password should contain at least one digit or letter. When the password meets all the requirements,ask user to enter password again and do not let the user continue until the second password matches the first one.
My code is as follows but it is not checking the letter or digit.
Can anyone help?
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
public class Password{
public static void main(String[] args){
String firstPassword="";
String secondPassword="";
char charChecked;
boolean letter = false;
boolean digit = false;
int len=firstPassword.length();
firstPassword= JOptionPane.showInputDialog("ENter");
if (( len<6 || len>10) || ! (Character.isLetterOrDigit(firstPassword.charAt(len))) )
{firstPassword= JOptionPane.showInputDialog("Enter the Correct Format of password");
}
if ((len>=6|| len<=10) || (Character.isLetterOrDigit(firstPassword.charAt(len))) )
do
{
secondPassword= JOptionPane.showInputDialog("Please enter again the password to confirm");
}
while (!(firstPassword.equals(secondPassword)));
if (firstPassword.equals(secondPassword))
{
JOptionPane.showMessageDialog(null,"Accepted");
}
}
}
int len=firstPassword.length();
firstPassword= JOptionPane.showInputDialog("ENter");
your code are inverted... you need to call the length after input something.
firstPassword= JOptionPane.showInputDialog("ENter");
int len=firstPassword.length();
Try and say something...
Related
Pretty basic question I believe... lets say I had this program and the access code had to specifically be 13 characters long. How would I make it so that if it wasn't 13 long then the user would have to retry and enter it again?
import java.util.Scanner;
public class access code
{
Scanner scan;
public void go()
{
String code = ("Enter your access code: ");
}
}
Per request, here's some explanation as to why this works. You need to repeatedly ask for information until the user enters something consisting of 13 characters. This code gets user input while the length of input is not 13. Which means that the loop terminates when the length is 13.
String input = "";
while (input.length() != 13){
System.out.print("Enter code: ");
input = scan.nextLine();
}
I'm new to programming and we were given our first assignment! My whole code is working fine, but here is my problem:
We have to prompt the user to enter in an account ID that consists of 2 letters followed by 3 digits.
So far I only have a basic input/output prompt
//variables
String myID;
//inputs
System.out.println("Enter your ID:");
myID = input.nextLine();
So all it does is let the user enter in how many letters and digits they want, in any order and length. I don't understand how to "control" the user's input even more.
As you said you are not aware of regex ,I have written this code to iterate by while loop and check if each character is a alphabet or digit. User is prompted to provide account number till the valid one is entered
import java.util.Scanner;
class LinearArray{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
boolean isIdValid = false;
String myId;
do{
System.out.println("account ID that consists of 2 letters followed by 3 digits");
myId = input.nextLine();
//Check if the length is 5
if (myId.length() == 5) {
//Check first two letters are character and next three are digits
if(Character.isAlphabetic(myId.charAt(0))
&& Character.isAlphabetic(myId.charAt(1))
&& Character.isDigit(myId.charAt(2))
&& Character.isDigit(myId.charAt(3))
&& Character.isDigit(myId.charAt(4))) {
isIdValid = true;
}
}
}while(!isIdValid);
}
}
So I have to write a program that prompts the user to enter a password that has to follow three requirements: at least 8 characters long, only letters and digits, and at least two digits. Now the method I created to check these three requirements I believe is sound, but my program also has to do some exception handling and be able to ask the user to reenter the password if one of the requirements is off and display the respective error message to go along with each requirement. I created a string errorMessage to relay that message but it gives me an error when i try to call it in my main ?
My other issue is that the password must be taken in to my program by using JPasswordField but I am struggling with even setting it up because of the numerous other factors like the JPanel, buttons, and action events that I read has to go along with it. I attempted to use JPasswordField and noticed that the line that takes in the password, takes it in as an array, when my checkPassword method needs a string, how can i take in that password as a string instead?
This is what I have for my program so far:
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javafx.event.ActionEvent;
public class Ed10Chp6Ex6Point18CheckPasswordProgram {
public static void main(String[] args) {
final JFrame frame = new JFrame("Check Password Program");
JLabel jlbPassword = new JLabel("Please enter the password: ");
JPasswordField jpwName = new JPasswordField(15);
jpwName.setEchoChar('*');
jpwName.addActionListener(new ActionListener()) {
public void actionPerformed(ActionEvent e) {
JPasswordField input = (JPasswordField) e.getSource();
char[] password = input.getPassword();
if(checkPassword(password)){
JOptionPane.showMessageDialog(frame, "Congradulations, your password follows all the requirements");
}
else{
JOptionPane.showMessageDialog(frame, errorMessage);
}
}
}
}
public static boolean checkPassword(String x) {
String errorMessage = "";
//must have at least eight characters
if (x.length() < 8){
errorMessage = "The password you entered is invalid, password must be at least 8 characters";
return false;
}
//consists of only letters and digits
for (int i = 0; i < x.length(); i++) {
if (!Character.isLetter(x.charAt(i)) && !Character.isDigit(x.charAt(i))) {
errorMessage = "The password you entered is invalid, password must contain only letters and digits";
return false;
}
}
//must contain at least two digits
int count = 0;
for (int i = 0; i < x.length(); i++) {
if (Character.isDigit(x.charAt(i))){
count++;
}
}
if (count >= 2){
return true;
}
else {
errorMessage = "The password you entered is invalid, password must contain at least two digits";
return false;
}
}
}
I apologize in advanced in case some of my questions seem rudimentary, any help would be greatly appreciated, thank you!
Two things right off the bat:
(1) Make sure you are importing the correct classes, don't rely on an IDE to do proper imports. You are importing the ActionEvent class from JavaFX, but the framework you are working with is Swing.
Change
import javafx.event.ActionEvent;
To
import java.awt.event.ActionEvent;
I am not very familiar with how nicely JavaFX and Swing play with one another, but using the correct classes typically helps avoid headaches and compile/runtime errors.
(2) A static method in the java.lang.String class provides a convenient way to convert a char array into a string. In your actionPerformed method, add this:
String passStr = String.valueOf(password);
E.g.
#Override
public void actionPerformed(ActionEvent e) {
// Get the source of the event, we know it is a JPasswordField so we cast it.
JPasswordField input = (JPasswordField) e.getSource();
// Get the char array from the input the user typed stored in the input object.
char[] password = input.getPassword();
// Convert char[] to String
String passwordStr = String.valueOf(password);
if(checkPassword(passwordStr)){
JOptionPane.showMessageDialog(frame, "Congradulations, your password follows all the requirements");
} else {
JOptionPane.showMessageDialog(frame, errorMessage);
}
}
how can i take in that password as a string instead
Either checkPassword(new String(input.getPassword)) or update your method to accept a char[] instead of a String.
As for error checking, you should use throw new ShortPasswordException(), where you want to throw that error, after you implement a class like ShortPasswordException extends Exception, for example.
Then, you can do
try {
checkPassword();
} catch (ShortPasswordException e) {
// TODO: Handle exception
}
Tip for the more adventurous: Use a regular expression to check your password requirements. A match of \d{2}, for example, means you have 2 consecutive digits.
My problem is to create a password that contains between 6 and 10 characters and contains at least one letter and one digit, and then to have the user re-enter the password and confirm that they match.
The only issue I have is checking to see if the password has a letter or digit. I have browsed and found the same problem on the website, but I was confused about some of the methods and other things they referenced in their code since I seemed to build mine differently. I thought about using the indexOf() method to see if it returned a -1 value, but I'm not really sure where to begin.
I'm really new at java and I'm sure there is a much more efficient way to construct this, and I would love any tips.
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
//Input from user
String password;
Scanner input = new Scanner(System.in);
System.out.print("Please create your password: ");
password = input.nextLine();
//Checking password length
while( (password.length() < 6) || (password.length() > 10) )
{
System.out.print("This password must be between 6 and 10 characters. Try again: ");
password = input.nextLine();
}
//Checking to see if passwords contain digit/letter
/*Need to add code here */
//Confirming if passwords match
String password2;
System.out.print("\nPlease type your password again to confirm: ");
password2 = input.nextLine();
while( !password2.equals(password) )
{
System.out.print("Those passwords do not match. Try again: ");
password2 = input.nextLine();
}
}
}
With Regex
You should use a regular expression, to check for theese crits.
First, the code:
pwd.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,10}$")
Here's a full example:
public class HelloWorld{
public static void main(String []args){
String password = "aA2";
String regexp = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,10}$";
System.out.println(password.matches(regexp));
password = "12345678";
System.out.println(password.matches(regexp));
password = "aA345678";
System.out.println(password.matches(regexp));
}
}
gives the following output:
false
false
true
The regexp matches any string, that conatins at least upper case, one lower case letter and one digit, and 6 - 10 character long.
You can find more examples of theese here. And some info about the regexps on the Wikipedia. A very good tutorial about regexps and Java can be found on Vogella. (It's a very good site, with very good tutorials, I think!) And, a handy tool to display what a regexp matches: http://www.regexper.com/
In case of the previous example, it gives you a very visually output.
Without Regexs
So, if you cannot use Regulax Expressions, I would create a function, which returns true, if the password is OK, false in any other case. Here's a small example for this function:
public static boolean passwordOk(String password){
if (password == null) return false;
if (password.length() < 6 || password.length() > 10) return false;
boolean containsUpperCase = false;
boolean containsLowerCase = false;
boolean containsDigit = false;
for(char ch: password.toCharArray()){
if(Character.isUpperCase(ch)) containsUpperCase = true;
if(Character.isLowerCase(ch)) containsLowerCase = true;
if(Character.isDigit(ch)) containsDigit = true;
}
return containsUpperCase && containsLowerCase && containsDigit;
}
The main idea thing in this solution, is a for-each loop. I create a character array from the String, and loop over the elements of it. If the current character is a digit, or uppercase, or lowercase, I set a flag, to sign, that one of the statements are true. At the beginning, all of the statements are false, and at the end I'll return the result of their sum.
In the first two lines I check, if the argument isn't null, and if it has the right length.
I hope, that after this you'll be able to solve your homework! You can call this function even with null pointers, so I would create a while loop, to run while this function do not returns true.
If it's hopeless, to solve this problem, here's the full code.
Believe me, it'll be more useful, if you try to solve this by your own, first!
You can use something like this...
if( password.matches(".*[a-zA-Z]+.*")){
System.out.println( "Has characters ");
} else {
System.out.println("Ok");
}
This is to check if the password contains a letter
Similarly you can use the regular expression ".*[0-9]+.*" to check if the password contains a digit.
So let's imagine we have this loop that obtains input from the user in the form of strings. With that input, what we want to do is set up a set of validations that will check if certain criteria are met. If all of these conditions are met, it'll complete the action in question. However; if it doesn't, it'll tell them the error and restart the process.
My question is about validating the existance (or non-existance) of a letter in a string. I have this program and for one of these validations, I need to check the entire string. If the string does not have at least one character that isn't a letter, I want to halt the action and explain that a non-letter character is required.
The problem is that I am not sure how I could replicate this in an expression in an if loop. Here's what I have so far.
public static changePassword() // Method that runs through the process of changing the password.
{
// Retrieving the current and new password from the user input.
System.out.println("Welcome to the change password screen.");
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your current password: ");
String currentPassword = keyboard.nextLine();
System.out.print("Please enter the new password: ");
String newPassword1 = keyboard.nextLine();
System.out.print("Please enter the new password again: ");
String newPassword2 = keyboard.nextLine();
// Validating the new password entry.
if (newPassword1.equals(newPassword2)) // Checking to see if the new password was entered exactly the same twice.
{
if (newPassword1.length() >= 6) // Checking to see if the new password has 6 or more characters.
{
if (**some expression**) // Checking to see if the password has at least one non-letter character.
{
currentPassword = newPassword1 // If all conditions are met, it sets the current password to the password entered by the user.
}
else // If there isn't a non-letter character, it informs the user and restarts the process.
{
System.out.println("The new password must have a non-letter character.");
changePassword();
}
}
else // If there is less than 6 characters, it informs the user and restarts the process.
{
System.out.println("The new password can not be less than 6 characters.");
changePassword();
}
}
else // If the new passwords don't match, it informs the user and restarts the process.
{
System.outprintln("The passwords must match.");
changePassword();
}
}
Assuming by "letter" you mean an english character in A-Z, a-z, just iterate through the string and return true if you encounter a character whose int value is outside the letter range.
public static boolean containsNonLetter(String s){
for(int i = 0; i < s.length(); i++){
int ind = (int)s.charAt(i);
if(ind < 65 || (ind > 90 && ind < 97) || ind > 122)
return true;
}
return false;
}
I am making the assumption that by letter you meant alphabets. If you use regex pattern you can have a very clean code as well you have ability to update the pattern as necessary. To learn more check Java Pattern. Here is the code.
private static final Pattern APLHA = Pattern.compile("\\p{Alpha}");
public static boolean hasLetter(String input) {
return APLHA.matcher(input).find();
}