How to get program to print, if a boolean variable is true? - java

I know this seems like a very simple question, but keep in mind I am new to java. Attached is my source code and at the end I write and if statement to print out "Password is valid" if the variable "valid" is true. The code runs fine until it hits this point, at which instead of printing "password is valid", it exits the program? I have looked at numerous thread on stack overflow to see how this could be solved and most threads suggest that this code should work. Any advice would be appreciated. Thanks
import java.util.Scanner;
public class PasswordValidator {
public static void main(String[] args) {
//declare name and pass and insert scanner
Scanner sc = new Scanner(System.in);
String name = "name";
String pass = "pass";
// tell user to type name and password and store as variables
System.out.print("Enter user name: ");
name = sc.nextLine();
check(name); // check if name is equal to -1
System.out.print("Enter password: ");
pass = sc.nextLine();
validate(name,pass); // call method
}
static boolean validate(String userName, String password) {
//declare necessary variables
String upperCase = ".*[A-Z].*";
String lowerCase = ".*[a-z].*";
String number = ".*[0-9].*";
String special = ".*[^A-Za-z0-9 ].*";
boolean valid = true;
if (password.matches("-1")) { // if input for password is -1 exit program
System.exit(0);
}
if (password.matches(upperCase)) { // check to see if input has one upper case letter
valid = true;
}
else
System.out.println("Password should contain at least one upper-case alphabet.");
valid = false;
if(password.matches(lowerCase)) { // check to see if input has one lower case letter
valid = true;
}
else
System.out.println("Password should contain at least one lower-case alphabet.");
valid = false;
if (password.matches(number)) { // check to see if input has one number
valid = true;
}
else
System.out.println("Password should contain at least one number.");
valid = false;
if(password.matches(special)) { // check to see if input has a special char.
valid = true;
}
else
System.out.println("Password should contain at least one special character.");
valid = false;
if(password.length()>=7 && password.length() <= 10) { // make sure the password input = 7-10 char.
valid = true;
}
else
System.out.println("Password should be within 7 to 10 characters in length.");
valid = false;
if (password.matches(".*\\s.*")) { // check to see if input has white spaces
System.out.println("Password should not contain whitespace.");
valid = false;
}
if(password.matches(userName)) { // give error if user name and password are the same
System.out.println("Password should not contain or be the same as username.");
valid = false;
}
// this is where I try to print if password is valid. for some reason my program just exits without printing :(
if(valid==true) {
System.out.print("Password is valid");
}
return valid;
}
// method used to check if user name is -1, and close program if so
static boolean check(String userName) {
if (userName.matches("-1")){
System.exit(0);
}
return true;
}
}

The problem here is the braces after else. You print some statement in else and then the valid flag is made false regardless of the condition being true or false. Also, close the scanner at the end. Also, you don't need to check if valid==true, you can simply put it in the if condition. You code would look like
package com.digit.main;
import java.util.Scanner;
public class PasswordValidator {
public static void main(String[] args) {
// declare name and pass and insert scanner
Scanner sc = new Scanner(System.in);
String name = "name";
String pass = "pass";
// tell user to type name and password and store as variables
System.out.print("Enter user name: ");
name = sc.nextLine();
check(name); // check if name is equal to -1
System.out.print("Enter password: ");
pass = sc.nextLine();
validate(name, pass); // call method
sc.close();
}
static boolean validate(String userName, String password) {
// declare necessary variables
String upperCase = ".*[A-Z].*";
String lowerCase = ".*[a-z].*";
String number = ".*[0-9].*";
String special = ".*[^A-Za-z0-9 ].*";
boolean valid = true;
if (password.matches("-1")) { // if input for password is -1 exit program
System.exit(0);
}
if (password.matches(upperCase)) { // check to see if input has one upper case letter
valid = true;
} else {
System.out.println("Password should contain at least one upper-case alphabet.");
valid = false;
}
if (password.matches(lowerCase)) { // check to see if input has one lower case letter
valid = true;
} else {
System.out.println("Password should contain at least one lower-case alphabet.");
valid = false;
}
if (password.matches(number)) { // check to see if input has one number
valid = true;
} else {
System.out.println("Password should contain at least one number.");
valid = false;
}
if (password.matches(special)) { // check to see if input has a special char.
valid = true;
} else {
System.out.println("Password should contain at least one special character.");
valid = false;
}
if (password.length() >= 7 && password.length() <= 10) { // make sure the password input = 7-10 char.
valid = true;
} else {
System.out.println("Password should be within 7 to 10 characters in length.");
valid = false;
}
if (password.matches(".*\\s.*")) { // check to see if input has white spaces
System.out.println("Password should not contain whitespace.");
valid = false;
}
if (password.matches(userName)) { // give error if user name and password are the same
System.out.println("Password should not contain or be the same as username.");
valid = false;
}
// this is where I try to print if password is valid. for some reason my program
// just exits without printing :(
if (valid) {
System.out.print("Password is valid");
}
return valid;
}
// method used to check if user name is -1, and close program if so
static boolean check(String userName) {
if (userName.matches("-1")) {
System.exit(0);
}
return true;
}
}

Your else clauses do not include braces and thus you blindly set valid to false many many times. Also, you don't want to set valid back to true once it has failed a test. Fixing both of those issues should give you something like,
static boolean validate(String userName, String password) {
// declare necessary variables
String upperCase = ".*[A-Z].*";
String lowerCase = ".*[a-z].*";
String number = ".*[0-9].*";
String special = ".*[^A-Za-z0-9 ].*";
boolean valid = true;
if (password.equals("-1")) {
System.exit(0);
}
if (!password.matches(upperCase)) { // check to see if input has one upper case letter
System.out.println("Password should contain at least one upper-case alphabet.");
valid = false;
}
if (!password.matches(lowerCase)) { // check to see if input has one lower case letter
System.out.println("Password should contain at least one lower-case alphabet.");
valid = false;
}
if (!password.matches(number)) { // check to see if input has one number
System.out.println("Password should contain at least one number.");
valid = false;
}
if (!password.matches(special)) { // check to see if input has a special char.
System.out.println("Password should contain at least one special character.");
valid = false;
}
if (password.length() < 7 || password.length() > 10) { // make sure the password input = 7-10 char.
System.out.println("Password should be within 7 to 10 characters in length.");
valid = false;
}
if (password.matches(".*\\s.*")) { // check to see if input has white spaces
System.out.println("Password should not contain whitespace.");
valid = false;
}
if (password.matches(userName)) { // give error if user name and password are the same
System.out.println("Password should not contain or be the same as username.");
valid = false;
}
if (valid) {
System.out.println("Password is valid");
}
return valid;
}

You should put your all else parts like this with brackets,
ex:
Instead of using this
else
System.out.println("Password should be within 7 to 10 characters in length.");
valid = false;
Please use it like this
else
{
System.out.println("Password should be within 7 to 10 characters in length.");
valid = false;
}
You should do this to all your else parts and it should work.
If you use else without brackets only the first line that comes after else will be inside else. Thats the error you do here. Also you can improve your code by removing unnecessary assigns to false and true always if you take a good look at how it will execute

Related

Checking if a string contains only digits ? (isDigitMethod required)

The user should give a string, where we should check if all characters are numbers.
If all are digits, we will get one message that the password is with digits and move on with the program. If any of them (or all) is not a digit, then the user should enter password again.
(E.g. 465486 is acceptable. hell3429384 or sfdkjsfkj is not acceptable)
Apparently, my code is not working correctly, since whether I give a number or a letter to the password, I get the same result.
Am I looping something wrong, or am I using the isDigit method wrong?
import java.util.*;
public class Password {
public static void main(String[] args) {
Scanner passn = new Scanner(System.in);
System.out.println("Give password: ");
String pass = passn.nextLine(); /* user enters password*/
int length = pass.length();
boolean isadigit;
for(int i = 0; i < length; i++) { /*looping each character one by one*/
char character= pass.charAt(i);
if (Character.isDigit(i)) { /*checking if each character is digit*/
isadigit = true; /* if it is, give the value to isadigit true*/
System.out.println("PASSWORD is w digits");
}
else {
System.out.println("PASSWORD w/out digits");
passn.nextLine();
}
}
}
}
If you can use java-8 there is one-liner:
pass.chars().allMatch(Character::isDigit)
You are not checking each character, but each index value.
Change
if(Character.isDigit(i))
to
if(Character.isDigit(character))
Also: you don't break out of the loop when you encounter a non-digit...
A side note if you are on Android:
You can use TextUtils.isDigitsOnly() directly, e.g.
TextUtils.isDigitsOnly(myString)
And just in case, an empty string is digit only because it doesn't contain any non-digit; also this method is not null-tolerant.
To be honest: You could write code like you did. But it would be better to use a regular expression on that. You want to know, if a certain String only contains digits. Here is the code:
String foo = "My_pwd_is_wrong_123!";
String bar = "123";
boolean foo_ok = foo.matches("^[0-9]*$") // Will be "false"
boolean bar_ok = bar.matches("^[0-9]*$") // Will be "true"
Ok, in that case: Your Problem is, that you continue your loop after identifiyng a non-digit in one Password. You need to BREAK your loop, as soon as you find a non-digit in the pwd:
public class TEST {
public static void main(String[] args) {
Scanner passn = new Scanner(System.in);
System.out.println("Give password: ");
String pass = passn.nextLine(); /* user enters password*/
int length = pass.length();
boolean isadigit = true;
for(int i = 0; i<length; i++) { /*looping each character one by one*/
char character= pass.charAt(i);
if (!Character.isDigit(character)) { /*checking if current character is digit*/
isadigit = false; /* if it is not, give the value to isadigit false*/
break;
}
}
if(isadigit)
System.out.println("PASSWORD is w digits");
else
System.out.println("PASSWORD w/out digits");
}
}
Please see this sample implementation
boolean isDigit = false;
for (int i = 0; i < length; i++) {
char character = pass.charAt(i);
if (Character.isDigit(character)) {
isDigit = true;
} else {
passn.nextLine();
}
}
if (isDigit) {
System.out.println("PASSWORD is w digits");
} else {
System.out.println("PASSWORD w/out digits");
}
In Kotlin, you can use
text.all { it.isDigit() }
try to parse the string to Integer.
catch the exception
Scanner passn = new Scanner(System.in);
System.out.println("Give password: ");
String pass = passn.nextLine(); /* user enters password*/
try
{
Integer.parseInt(pass);
System.out.println("Digital password!");
}
catch(NumberFormatException nfe){
System.out.println("without digit password!");
}

JAVA: Password criteria

The prompt is:
Write a Java program to read a string (a password) from the user at the command line and then check that the password conforms to the corporate password policy.
The policy is:
1) the password must be at least 8 characters
2) the password must contain one upper case letter
3) the password must contain one digit.
Use a while loop to step through the string.
Output “Password OK” if the password conforms, otherwise
Output “Password does not conform to the policy.”
I have this down, and it seems to not work still:
String password = "";
boolean hasDigitAndUpper = false;
boolean hasUpper = false;
int i = 0;
System.out.print("Please enter a password: ");
password = scnr.nextLine();
if (Character.isUppercase(password.charAt(i))){
if (Character.isUppercase(password.charAt(i))) {
i++;
hasDigitAndUpper = true;
}
}
while (password.length() < 8 || hasDigitAndUpper != true) {
System.out.println("Password does not conform to policy");
System.out.print("Please enter a password: ");
password = scnr.nextLine();
}
System.out.println("Password OK");
I guess my biggest issue is my boolean which I can't figure out how to fix.
Just some hints:
if (Character.isUppercase(password.charAt(i))){
if (Character.isUppercase(password.charAt(i))) {
i++;
hasDigitAndUpper = true;
}
}
Further down you are using a while-loop. So you have heard of loops before. Hint: you want to for-loop the whole string and check all chars. In my passwords, the uppercase characters usually turn up later behind index 0 or 1.
Then:
while (password.length() < 8 || hasDigitAndUpper != true) {
System.out.println("Password does not conform to policy");
System.out.print("Please enter a password: ");
password = scnr.nextLine();
}
Will not do anything reasonable. You want that loop around the other code. This code just loops and asks the user to enter a new password that has 8 chars - that other boolean hasDigitAndUpper has its old value.
So: you want to write one little method per criteria; and then your code goes:
while (not-all-criteria) {
password = new user input
check password length
check password has upper case
...
Hope that is enough to get you going , and please understand that I am not going to do your homework for you. You are in urgent need to practice those things yourself!
You can use this simple function. This iterates over the password and checks the conditions. If all conditions are satisfied then it returns true, Else false.
public static boolean isValid(String pwd)
{
if (pwd == null || pwd.length() < 8)
{
return false;
}
boolean containUpper = false;
boolean containDigit = false;
int i = 0;
while (i < pwd.length())
{
if (containDigit && containUpper)
{
break;
}
if (Character.isUpperCase(pwd.charAt(i)))
{
containUpper = true;
}
if (Character.isDigit(pwd.charAt(i)))
{
containDigit = true;
}
i++;
}
return containDigit & containUpper;
}

Java trouble checking if password string is valid

So I'm trying to get this to take user input as a string and check the password to make sure of these two things:
The password is a minimum of 8 characters.
The password only contains letters and numbers.
Now the problem is this:
Checking the password for a minimum of 8 characters works, but checking it to make sure it only contains letters and numbers does not work. It simply terminates without giving a single message if the minimum amount of numbers/letters are entered. However if it sees a character that is not a letter or number, it will print out this:
Please enter a password: ###
Password can only contain letters and numbers.
Password can only contain letters and numbers.
Password can only contain letters and numbers.
Password accepted!
What it should output is this:
Please enter a password: ###
Password can only contain letters and numbers.
or
Please enter a password: test1234
Password accepted!
password.java
package Password;
import java.util.Scanner;
public class Password {
public static void main(String[]args)
{
Scanner input = new Scanner (System.in);
boolean valid = true;
System.out.println("Please enter a password:");
String password = input.nextLine();
int i = 0;
//declares i as the counter varible to control the loop and initializes it to 0
if((password.length( ) < 8 )) //check the passwords length and make sure it's a minimum of 8 characters
{
System.out.println("Password must have at least 8 characters.");
valid = false;
}
//loops the code below it for the length of i until the password length is reached
while(i < password.length())
{
if ((password.charAt(i)>='a' && password.charAt(i)<='z') || (password.charAt(i)>='A' && password.charAt(i)<='Z') ||(password.charAt(i)>='0' && password.charAt(i)<='9'))
//loop through all the characters in the string entered and make sure they only consist of letters and numbers
valid = true;
else
{
System.out.println("Password can only contain letters and numbers.");
valid = false;
}
i++;
//add an iteration to the loop
}
if(!valid == true)
System.out.println("Password accepted!");
}
}
Any help at all with this would be great.
You could simplify the code a bit, first start with valid by checking the password.length(); then test each character in the password (stopping if any are invalid). Then finally check if the password was valid before displaying your accepted message. Like,
Scanner input = new Scanner(System.in);
System.out.println("Please enter a password:");
String password = input.nextLine();
boolean valid = password.length() >= 8;
if (!valid) {
System.out.println("Password must have at least 8 characters.");
} else {
for (char ch : password.toCharArray()) {
if (!Character.isLetter(ch) && !Character.isDigit(ch)) {
System.out.println("Password can only contain letters and numbers.");
valid = false;
break;
}
}
}
if (valid) {
System.out.println("Password accepted!");
}
the main error in this check code is the while loop,when you see a wrong character there is no need to continue the loop,simply you do this kind of checks in that way :
String toCheck; //the string to check some criteria
boolean valid = true; // we assume that nothing wrong happen till now
for(int i=0;i<toCheck.length();i++){ //loop over the characters
if(/*condition of wrong case*/){
valid = false; //mark that something wrong happen
break; //exit the loop no need to continue
}
}
if(valid){
//nothing wrong happen
} else {
//something wrong happen
}

Creating and validating a reference number

So basically, I need to get the user to enter a reference number; it cannot be automatically generated.
It needs to be 2 Numbers, a Letter and a Number again.
Here's my code, but I cannot for the life me get it working, I had it working via a way that automatically generates a reference number, but now we need to change it so it gets the user to manually generate one and I'm just sat staring at NetBeans like "Oh errmmmm..."
static String getReferenceNumber() {
Scanner refScanner = new Scanner(System.in);
String referNumber = null;
System.out.println("Please enter a Reference Number");
System.out.println("It must be 2 Letters and 3 Numbers and a Number");
String input = refScanner.nextLine().toUpperCase();
while (!Policy.refCheck(input)) {
System.out.println("Please enter a Reference Number");
System.out.println("It must be 2 Letters and 3 Numbers a Nuber");
if (input.length() !=5) {
referNumber = false;
} else if ((!Character.isLetter(input.charAt(0)))
||!Character.isLetter(input.charAt(1))
||!Character.isDigit(input.charAt(2))
||!Character.isDigit(input.charAt(3))
||!Character.isDigit(input.charAt(4))){
referNumber = false;
}
System.out.println("");
System.out.println(referNumber);
return referNumber;
}
You never assign the actual input to the referNumber, instead you just assign Booleans?
Therefore at the end you are returning a Boolean or null when the return value needs to be a string.
static String getReferenceNumber() {
Scanner refScanner = new Scanner(System.in);
String referNumber = "";
boolean test = false;
while (!test) {
System.out.println("Please enter a Reference Number");
System.out.println("It must be 2 Letters and 3 Numbers:");
String input = refScanner.nextLine().toUpperCase();
if (input.length() !=5) {
test = false;
System.out.println("Invalid reference");
} else if ((!Character.isLetter(input.charAt(0)))
||!Character.isLetter(input.charAt(1))
||!Character.isDigit(input.charAt(2))
||!Character.isDigit(input.charAt(3))
||!Character.isDigit(input.charAt(4))){
test = false;
System.out.println("Invalid reference");
} else {
referNumber = input;
test = true;
}
}
System.out.println(referNumber);
return referNumber;
}
I have changed the condition for the while loop and altered your if statements. I hope this helps.

Checking for repeated characters in password using Java

I'm a student of CIS taking a Java class (hoping to become a programmer). Anyhow, I have an assignment to create a program that checks a password for validity. If the password is not valid, it is to print a message. If the password is valid, the user is to reinsert the password. If they both match, it is to print a message accepting. If they do not match, it is to print a message.
The password requirements are:
Must be at least 8 characters in length
Must contain one number
Must contain one letter
Must contain one special character
Cannot have 3 or more identical characters
Cannot contain spaces
Cannot start with ! or ?
I am using netbeans.
package pass1;
import java.util.Scanner;
public class Pass1 {
//Main method asks for pasword from user and calls upon methods to verify password requirements and password 1 and 2 match
public static void main(String[] args) {
//declare variables
String pass1;
String pass2;
boolean passvalid;
boolean passmatch;
//initialize new instance of scanner
Scanner kb = new Scanner(System.in);
//get password
System.out.println("Please input password. (Must be at least 8 characters, contain a number, letter, and special character");
pass1 = kb.nextLine();
//initialize instance of passisvalid to check password for requirements
passvalid = passisvalid(pass1);
//if pass is valid, allow user to reinsert password
if (passvalid){
System.out.println("Please reinsert password:");
pass2 = kb.nextLine();
//initialize instance of passismatch to check passwords match
passmatch = passismatch(pass1, pass2);
//if passwords do not match, print message
if (!passmatch)
{
System.out.println("Passwords do not match.");
}
//if passwords match, print message
else if (passmatch)
{
System.out.println("Password set.");
}
}
//if password is not valid, print message
else
{
System.out.println("Password is not valid:");
}
}
/*************************************************************************************/
//this method check that user inputted password meets requirements, and returns boolean value
public static boolean passisvalid(String password) {
//declare variables
boolean letter;
boolean digit;
boolean space;
boolean length;
boolean start1;
boolean start2;
boolean valid;
boolean special;
//initialize variables
valid=false;
letter=false;
digit=false;
space=false;
special=false;
length = false;
start1=false;
start2=false;
//initialize count
for(int i=0;i<password.length();i++)
{
char s=password.charAt(i);
//check for letter in password
if(Character.isLetter(s))
{
letter = true;
}
//check for number in password
if(Character.isDigit(s))
{
digit = true;
}
//check for spaces in password
if(Character.isSpaceChar(s))
{
space=true;
}
//check for special characters in password
if(!Character.isDigit(s) && !Character.isLetter(s))
{
special=true;
}
}
//check password length
if (password.length() > 8)
{
length=true;
}
//check password start with ? or !
else if (password.startsWith("?"))
{
start1=true;
}
else if (password.startsWith("!"))
{
start1=true;
}
//requirements of password for boolean true
if(letter && digit && special && length)
{
valid = true;
}
//return boolean false if detect start with ? or !, or spaces in password
if(start1||start2||space)
{
valid = false;
}
return valid;
}
/**********************************************************************************/
//this method checks that both user entered passwords match
public static boolean passismatch(String password1, String password2){
//declare variables
boolean match;
//initialize variables
match=false;
//compare password strings
if (password1.equals(password2))
{
match= true;
}
return match;
}
}
So I've been able to figure all except for making sure there are no consecutive repeating characters. I really don't even know where to begin with this. I've searched for hours on a few forums to try and find a solution and put it all together but without seeing an example or just something I can't figure it out for the life of me. Any help would be IMMENSELY appreciated.
You can get password to string array and compare each string with the next two string whether it has the same.
public static boolean hasConsecutiveCharacters(String pwd){
String[] letter = pwd.split(""); // here you get each letter in to a string array
for(int i=0; i<letter.length-2; i++){
if(letter[i].equals(letter[i+1]) && letter[i+1].equals(letter[i+2])){
return true; //return true as it has 3 consecutive same character
}
}
return false; //If you reach here that means there are no 3 consecutive characters therefore return false.
}
package filehandling;
import java.util.Scanner;
public class PasswordValidation {
public static void main(String[] args) {
String enterPassword ;
String reEnterPassword ;
boolean passValid ;
boolean isPassMatch ;
Scanner password = new Scanner(System.in);
System.out.println("Enter Your Password:");
System.out.println("(Must be at least 8 characters, contain a number, letter, and special character");
enterPassword = password.nextLine();
passValid = checkPassIsValid(enterPassword);
if(passValid) {
System.out.println("Re-Enter Your Password: ");
reEnterPassword = password.nextLine();
isPassMatch = checkPasswordMatching(enterPassword,reEnterPassword);
if(!isPassMatch)
System.out.println("Password do Not Match: ");
else if (isPassMatch)
System.out.println("Password Set.");
}
else
System.out.println("Password is Not Valid.");
}
private static boolean checkPassIsValid(String enterPassword) {
boolean length = false;
boolean letter = false;
boolean digit = false;
boolean space = false;
boolean startSpace = false;
boolean special = false;
boolean start1 = false;
boolean start2 = false;
boolean valid = false;
for(int i = 0; i < enterPassword.length(); i++) {
char c = enterPassword.charAt(i);
if(enterPassword.length() >= 8)
length = true;
if(Character.isDigit(c))
digit = true;
if(Character.isLetter(c))
letter = true;
if(Character.isSpaceChar(c))
space = true;
if( (!Character.isDigit(c)) && (!Character.isLetter(c)) )
special = true;
if(enterPassword.startsWith(" "))
startSpace = true;
else if(enterPassword.startsWith("?"))
start1 = true;
else if(enterPassword.startsWith("!"))
start2 = true;
if(letter && digit && special && length)
valid = true;
if(start1 || start2 || startSpace)
valid = false;
}
return valid;
}
private static boolean checkPasswordMatching(String enterPassword,String reEnterPassword) {
if(enterPassword.equals(reEnterPassword))
return true;
return false;
}
}

Categories

Resources