How to fix boolean method in string - java

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.

Related

Having trouble getting a Regular expression program running

import java.util.Scanner;
public class VerifySerialBayneHarris {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String text;
String cha;
System.out.println("Enter a Serial number: ");
text=input.nextLine();
if(text.matches("[^-](?!.*--)[A-Za-z0-9-]+[^-]"));{
System.out.println("Serial number "+text+" verification \nValid");
System.out.println("Enter a wildchar character: ");
cha=input.nextLine();
text= text.replaceAll("[A-Za-z0-9]", cha);
}
if(text.matches("[^A-Za-z0-9-]+"));
System.out.println("Only uppercase , lowercase letters, dashes and numbers are allowed.It should have exactly 2 non-consecutive dashes in the middle. ");
}
}
This is what I have so far, but I keep getting both of the expressions running instead of one or the other. There must be something I'm missing. Thanks in advance.
Here is my guidelines:
prompts the user to enter a serial number according to the following rules:
Only uppercase and, lowercase letters, dashes and numbers are allowed.
It should have exactly 2 non-consecutive dashes in the middle.
Your program should verify that the serial number is valid and if so, prompt the user to enter a wildcard character. It should then display the concealed serial number by masking all of its characters except the dashes using the wild char character
[What code is supposed to look like]
[1]: https://i.stack.imgur.com/xoGke.jpg
Get rid of the semi-colon here...
if(text.matches("[^-](?!.*--)[A-Za-z0-9-]+[^-]"));{ << HERE
...and...
if(text.matches("[^A-Za-z0-9-]+")); << HERE
Your blocks are always executing because the if statement has an empty block due to this.
If you have minus in character class then it should be first:
[A-Za-z0-9-] shall be [-A-Za-z0-9]
But I would not include the - in the groups and write the pattern as: [A-Za-z0-9]+(-[A-Za-z0-9]+){2}
Or with POSIX: \p{Alnum}+(-\p{Alnum}+){2}
If you want to access the 3 segments: (\p{Alnum}+)-(\p{Alnum})-(\p{Alnum})

How can I validate a phone number input of several variations?

My program currently validates the phone number only when it is ten consecutive numbers and characters and it closes when the word "exit" is typed. However, I was wondering how I could validate the numbers if they were also written as both, for example, (123)456-7890 and 123-456-7890
import java.util.Scanner;
public class Q2
{
public static void main(String[] args){
Scanner kb=new Scanner(System.in);
while (true){
System.out.print("Enter your phone number: ");
String number=kb.next();
if(number.equals("exit")){
System.exit(0);
}
boolean valid=true;
for(int i=0;i<number.length();i++){
if(number.length()!=10) valid=false;
}
if (valid) System.out.println("It is valid");
else System.out.println("It is invalid");
}
}
}
You do that by doing real validation.
Meaning: "validation" describes the process of checking your input against a set of rules. If the input conforms to all those rules, it is valid; otherwise it is not.
So, yes, checking the length was a first simple rule; but "length is 10" ... just turns out to not be a good rule. For example, "123456A90" has length 10; but is invalid.
What you can do instead (just giving you some ideas):
use regular expressions (or plain string parsing) in order to determine if your input string matches a certain pattern, like (nnn-nnnn-nnnn)
simple replace all "unwanted" characters, such as ( ) - with ""; and then you check if the resulting string has length 10.
So, the answer is: have a close look at your input and determine the properties that valid phone numbers have in common. And then you start writing code to check those.
Why you simply don't use regex like this its more powerful :
public static void main(String[] args) {
System.out.println("123-456-7890 is valid? " + valider("123-456-7890"));
System.out.println("(123)456-7890 is valid? " + valider("(123)456-7890"));
}
private static boolean valider(String phoneNumber) {
if (phoneNumber.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) {
return true;
} else return phoneNumber.matches("\\(\\d{3}\\)\\d{3}-\\d{4}");
}

How to Validate Canadian postal Code in Java? Checking for 2 types of input? ex: accepting A1A1A1 and A1A 1A1

I am trying to make a program that allows the user to input 2 different formats for a postal code (A1A1A1 or A1A 1A1) and I cannot for the life of me get it to work :/
My thought process was identifying both formats first and then using an if statement to check for the identified formats and then decide if its valid or not.
But I keep getting invalid when I try to enter the format with space in them (A1A 1A1).
so far I have this
import java.util.Scanner;
import java.util.regex.Pattern;
public class ValidatingPostcodes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a Postcode:");
String Pc1 = "[A-Z][0-9][A-Z][0-9][A-Z][0-9]";
String Pc2 = "[A-Z][0-9][A-Z][ ][0-9][A-Z][0-9]";
while (sc.hasNext())
{ if (sc.hasNext (Pc1))
System.out.println ("Valid Postal Code");
else if (sc.hasNext (Pc2))
System.out.println ("Valid Postal Code");
else System.out.println("Invalid Postal Code");
sc.next();
}
}
}
The easy solution is: simply treat the two kinds of input the same way when processing them internally. Meaning:
Create one method that validates a 6-char potential ZIP code
But before calling that method, you check if your input contains a space as 4th character, and if so, you simply remove that space before giving it as parameter to your validation method.
But keep in mind: you probably want to keep the original string around - if you intend to give back "A1A A2A" later on. Of course, if you decide that users can enter ZIPs in two ways, but that they should get back "unified" format later on, then you can make that "space-dropping" thing permanent.
EDIT: you create a method
public boolean isValid(String zipCode) {
that returns TRUE for valid zipcodes that have 6 (SIX!) chars and no spaces
and another method
public String normalizeZipCode(String incoming) {
return incoming.replaceAll("\\s+","");
}
To be used like:
String zip1 = "A1A 1A1";
String zip2 = "A1A1A1";
String normalizedZip1 = normalizeZipCode(zip1);
String normalizedZip2 = normalizeZipCode(zip2);
System.out.println(isValid(normalizedZip1));
System.out.println(isValid(normalizedZip2));
The simple idea: if one format contains spaces, then just remove those spaces prior validation. In other words: you allow the user to enter data in two formats; but internally, you make sure that any usage of the second format is simply avoided, by turning it into the format that comes without spaces.

Java Password Pattern

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")

Java Password Checker

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.

Categories

Resources