Java Password Pattern - java

The password checker program is supposed to take user input of a username and password and output whether the password is valid or invalid.
I've been trying to use regex for this but am having an issue. The pattern works for all my rules but one, the username rule.
Also, is there a way to change the output from "true" or "false" to something custom?
My code so far:
import java.util.regex.*;
import java.util.Scanner;
public class validPassword {
private static Scanner scnr;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Variable Management
String un, pw, req; // Variable Variable
System.out.println("Please enter a username: ");
// ^Need to implement so if it matches the password it's invalid^
un = input.nextLine(); // Gathers user's username input
System.out.println("Please enter a password: ");
pw = input.nextLine(); // Gathers user's password input
req = "(?=.*[0-9])(?=.*[a-zA-Z]).{8,}";
System.out.println(pw.matches(req)); // Can I customize the output?
}
}
I appreciate any help! :)

You should be able to just initially check if it has that sub-sequence.
I would check that initially then check your password rules.
So something like this (using a regex):
// get username and password
if(pw.matches(".*"+Pattern.quote(un)+".*")){
System.out.println("Password can't have username in it...");
}
// make sure password follows rules...
Better would be to use the contains method on strings (docs).
if (pw.contains(un)) {...}
As far as customizing the output of matches you can't. You'll need to conditionally branch and do something different.

For the username check you can change the regex to
"(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])((?<!" + Pattern.quote(un) + ").(?!" + Pattern.quote(un) + ")){8,}"
which means at least 8 arbitrary characters that are not followed or preceded by the username. This is with negative lookbehind and negative lookahead just as you used the positive lookahead for the requirement that the three characterclasses are contained.
And regarding the custom output, just use a ternary expression:
System.out.println(pw.matches(req) ? "yehaw" : "buuuuuh")

Related

Java Scanner add optional user input prompts

What is the way to take some parameters as optional user input using java util Scanner? Below is my code. But, for all the parameters it's blocked till the user input is entered.
I want it to continue for second parameter in cases 'when the user input is entered and then pressed enter key' "OR" 'when just pressed enter key without entering any input'.
public class MainApplication {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter ordertypes in comma separated format (mandatory): " );
String orderOrActionTypes = in.next();
System.out.println("Enter orderAttributes (optional): " );
String orderAttributes = in.next();
System.out.println("Enter ActionAttributes (optional): " );
String actionAttributes = in.next();
}
}
You can still let the input but leave it empty.
When an input is required, the user can press Enter (which results on an empty string), and then you can test, whether the user typed something or not orderAttributes.isEmpty() and you do what you need based on the results.
Try using in.nextLine();, it may help.

How to fix boolean method in string

Imagine you are developing a software package for Amazon.com that requires users to enter their own passwords. Your software requires that users’ passwords meet the following requirements: The password should be at least 8 characters. The password should contain at least one uppercase and at least one lowercase letter. The password should contain at least one digit. The password may not contain a blank
Write a program that verifies that passwords are valid.
This is my code:
import java.io.*;
import java.util.Scanner;
public class assignment7{
public static boolean test(String password,Scanner input){
boolean valid=false;
while(input.hasNextLine()){
password=input.nextLine();
for(int i=0;i<password.length();i++){
char c=password.charAt(i);
if((password.length()>=8)&&
(Character.isUpperCase(c))&&
(Character.isLowerCase(c))&&
(Character.isDigit(c))&&
(Character.isWhitespace(c)))
valid=true;
}
}
return valid;
}
public static void main(String[]args)throws FileNotFoundException{
Scanner input=new Scanner(new File("password.txt"));
String password;
while(input.hasNextLine()){
password=input.nextLine();
System.out.println(password.trim());
boolean isvalid=test(password,input);
if(isvalid)
System.out.println("This is a valid password: "+password+"\n");
else
System.out.println("This is a invalid password: "+password+"\n");
}
System.out.println("This program prcoessed all data");
input.close();
}
}
Why does my code only read the first password and stop executing? Plus even my password is correct but it still print out invalid password?
My input file is:
asdF1k12
Mzj1kada45
jKl123oin
You have create a while loop to loop through the lines in two locations: in your main method and in your test method. The test method is consuming all input, leaving nothing more for the main loop.
You're already passing password to test correctly; just don't have a while loop within test.
You don't need to check the password length each loop; just test it once before the for loop on the characters.
A character cannot simultaneously be uppercase, lowercase, a digit, and (&&) whitespace. You'll need to test if it's uppercase, lowercase, or (||) a digit, which would make it not whitespace.
Right now you're setting valid to true if any of the characters meet the conditions. To make it so that valid is true if all of the characters meet the requirements, initialize valid to true and set it to false if the current character doesn't meet the requirement.
You may also decide not test empty lines at all depending on your exact requirements.

I need some guidance on the substring function in JAVA

I'm not sure where I am going wrong with this particular code. Could someone please lend me some guidance to this?
Here is my question as well as what I have attempted to have as an outcome.
Modify songVerse to play "The Name Game" (OxfordDictionaries.com), by replacing "(Name)" with userName but without the first letter.
Ex: If userName = "Katie" and songVerse = "Banana-fana fo-f(Name)!", the program prints:
Banana-fana fo-fatie!
Ex: If userName = "Katie" and songVerse = "Fee fi mo-m(Name)", the program prints:
Fee fi mo-matie
Note: You may assume songVerse will always contain the substring "(Name)".
Code that I tried this last time...and no matter what I put in I keep getting the same results. I've tried different scenarios of the "userName.substring()" and still have the same outcome.
import java.util.Scanner;
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse + userName.substring(1 , userName.length()); // this is where my problem is.
System.out.println(songVerse);
}
}
1 test passed
All tests passed
Run
Testing Katie and Banana-fana fo-f(Name)!
Output differs. See highlights below.
Your output
Banana-fana fo-f(Name)!tie
Expected output
Banana-fana fo-fatie!
Testing Walter and Banana-fana fo-f(Name)!
Output differs. See highlights below.
Your output
Banana-fana fo-f(Name)!lter
Expected output
Banana-fana fo-falter!
Testing Katie and Fee fi mo-m(Name)
Output differs. See highlights below.
Your output
Fee fi mo-m(Name)tie
Expected output
Fee fi mo-matie
Here you go.
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse.replace("(Name)", userName.substring(0));
System.out.println(songVerse);
}
}
here you removed first character already from userName, so at the second last line you again don't need to remove it.
and for the song Verse, you need to remove "(NAME)" from it, so here you can use
songVerse = songVerse.replace("(NAME)","");
songVerse = songVerse+userName;
The method substring(int begin, int end) let hoose/create a substring from the initial String indicating the numbers of chars from which the substring should begin and end or begin only. There are no other variants to edit a substring, while it will not become a part of a freshly made string (“String songVerse” in your case). The object.replace() method should change the indicated “Text” (in your case it’s a “(Name)”) onto anything that you’d like to be inserted instead of it independently on the quantity or type of the chars before or after the “Text”. The variant proposed by Nicholas K is correct and should work or you can try its shorter version, however the result will be the same:
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
songVerse = scnr.nextLine();
songVerse = songVerse.replace("(Name)", userName.substring(1));
System.out.println(songVerse);
}
}
The problem with your code is that you are not attempting to solve the problem that you described in your question.
Try following these steps:
Devise a list of steps written in English to solve the problem; pay attention to details.
Run the list of steps in step 1 by hand.
Convert the steps in step 1 to code.
Here are some hints:
You will be reading the lyrics one line at a time.
Some lines have a replacement and others do not.
You will receive the Name as input one time; generate the name replacement value one time and use it each time you perform a replacement.
Your code is terrible.
Here is some more about "Pay attention to details"
You do not have a loop in your code;
this will read one line of lyrics and perform one substitution.
Count the number of lines in the lyrics.
If the number of lines is greater than one,
then your technique is guaranteed to fail.
If you have a loop in your code but decided not to include it in your code,
stop lying in your questions.
We can not help you fix code that you pretend does not exist.
In a sane world,
the name to use for the substitutions will appear exactly one time.
Read it one time.
In order to replace (Name) in a string, you must first find (Name) in a string.
This is pretty easy
import java.util.Scanner;
public class NameSong {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
String userName;
String songVerse;
userName = scnr.nextLine();
userName = userName.substring(1); // Remove first character
songVerse = scnr.nextLine();
// Modify songVerse to replace (Name) with userName without first character
songVerse = songVerse.replace("(Name)", userName);
/* Your solution goes here */
System.out.println(songVerse);
}
}

How to find an invalid character or symbol inside a string

I'm creating a program that prints user details, first the user inputs their details and then the program correctly formats the details and prints them inside a formatted box. I want the program to read strings and see if the users have entered invalid characters. For example the code below requests for the users first name:
// this code below is used to find the largest string in my program, ignore if this wont interfere
String fname = scan.nextLine(); //main scan point.
//below is used to calculate largest string inputted by the user.
int input = 0;
int fnamelength1 = fname.length();
input = fnamelength1;
int longest = 0;
if(input > longest)
longest = input;
If at this point the user enters #~~NAME~~# as their name, the program currently allows that... I want to make the program read what the user has inputted and print a message if their input isn't correct for example contains invalid symbols.
EDIT:
I'm considering anything other than characters in the alphabet as invalid... any numbers or symbols would therefore be invalid.
VALID:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
Also valid:
' - .
This can be done using regular expressions with the String.matches method. Here you define a pattern and if the string matches your pattern then it can be considered valid:
String fname;
Scanner scan = new Scanner(System.in);
boolean invalidInput;
do{
System.out.println("Enter a valid name");
fname = scan.nextLine();
invalidInput = fname.matches("[^a-zA-Z'-]]");
if(invalidInput){
System.out.println("That's not a valid name");
}
}while (invalidInput);
System.out.println("Name: " + fname);
EDIT
With String.matches we can't make a global search of invalid characters (what we want in this case). So is better using Matcher.find for this:
String fname;
Scanner scan = new Scanner(System.in);
boolean invalidInput;
Pattern pattern = Pattern.compile("[^a-zA-Z'\\-\\s]");
do{
System.out.println("Enter a valid name");
fname = scan.nextLine();
invalidInput = pattern.matcher(fname).find();
if(invalidInput){
System.out.println("That's not a valid name");
}
}while (invalidInput);
System.out.println("Name: " + fname);
This time the pattern will validate any invalid character anywhere in the string.
One approach would be to use regular expressions, along with the String.matches() method.
As an example:
String fname;
... some code to get fname ...
boolean valid = fname.matches("[a-zA-Z]+");
valid should be true if and only if fname is a String containing alphabetic characters, and not empty.
If empty strings are also valid, then:
boolean valid = fname.matches("[a-zA-Z]*");
Look up the Java class Pattern for other variations.

Any ideas to mask the input?

I have been working on small project of mine which has the account name and account password as an array .
After the program runs it ask you to enter your username followed by password then it matches it with its database. If correct: proceed; if not: display login fail.
What I want is when the user enters the password instead of displaying the password as 1234 I want to show it as ****.
{
Scanner in = new Scanner(System.in);
public int UserNameAndPassword(){
System.out.println("Pleass Enter your username:");
String user =in.nextLine();
System.out.println("Pleass Enter your Password:");
String pin = in.nextLine();
int p= FindNameAndPassword(user,pin);
return p;
}
main
public static void main(String[] args) {
HelpingMethodes h =new HelpingMethodes();
Scanner in =new Scanner(System.in);
while(true)
{
int position,choise;
position = h.UserNameAndPassword();
boolean login = true;
while(position==-1)
{
System.out.println("You entered wrong Username or Password");
System.out.print("Pleas try again\n");
position=h.UserNameAndPassword()
}
Is there any simple way to achieve that in Java?
Consider Console.readPassword. Although it will not mask the password with *, it does the job as it hides the text inputted. Quick code snapshot:
char[] password = System.console().readPassword("Password: ");
System.out.println("Password is: "+ password);
Note: You must run the program via command line. If you're running this through an IDE, you will get null on the Console object.
You'll find a detailed tutorial here.
If you prefer not to use Console, you'd have to implement an alternative solution. You'd have to write a thread that overwrites the input as it's received, which won't be a trivial task. As far as I know, Scanner does not have a built-in masking method.
Trying using : http://docs.oracle.com/javase/6/docs/api/java/io/Console.html#readPassword() instead of Scanner.
Also, this is called password masking, not hashing, just FYI.

Categories

Resources