Validating a Password - java

I want to check whether a password has at least 8 characters and consist of numbers and letters only.
The problem here is even though I entered a valid password it says 'Invalid' all the time. Here's the code. Thanks.
public static void main(String[] args)
{
String pw;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a password: ");
pw = sc.next();
if(isValid(pw)==true)
{
System.out.println("Valid Password");
}
else
{
System.out.println("Invalid Password");
}
}
public static boolean isValid(String pw)
{
if(pw.length()<8)
{
return false;
}
else
{
for(int x=0; x<pw.length(); x++)
{
return Character.isLetterOrDigit(pw.charAt(x));
}
}
return true;
}
}

Logic of your code is correct except return statement in 'for' loop in isValid method. Here is edited code:
public static void main(String[] args)
{
String pw;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a password: ");
pw = sc.next();
if(isValid(pw))
{
System.out.println("Valid Password");
}
else
{
System.out.println("Invalid Password");
}
}
public static boolean isValid(String pw)
{
if(pw.length()<8)
{
return false;
}
else
{
for(int x=0; x<pw.length(); x++)
{
if(!Character.isLetterOrDigit(pw.charAt(x)))
return false;
}
}
return true;
}
Note that your code does not print 'invalid' if your password is valid but could print 'valid' for some invalid passwords such as a########

You're returning the result within the first iteration of the loop, rather you should make a flag variable and return the result at the end of the loop or you could invert the if condition within the loop and return false if that evaluates to true and if it does not then return true at the end of the loop.
public static boolean isValid(String password){
if(password.length() < 8)
return false;
for(int x = 0; x < password.length(); x++)
if(!Character.isLetterOrDigit(password.charAt(x)))
return false;
return true;
}

Related

The user must enter a string that is greater than 6 characters long

How can I code this using subroutines in java with a loop so if they don't get it right it keeps repeating till they do. This is all i have so far. The user must enter a string that is greater than 6 characters long.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package containsmethod;
import java.util.*;
import java.lang.String;
import java.lang.Character;
import java.util.Scanner;
public class ContainsMethod {
public static boolean isValid(String password) {
if (password.length() < 6) {
return false;
} else {
char c;
for (int i = 0; i < password.length() -1; i ++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (Character.isDigit(c)) {
return false;
}
}
}
return false;
}
public static void main (String [] args) {
Scanner input = new Scanner (System.in);
{
System.out.print ("Please enter a string that is greater than 6 characters long. ");
String password = input.next();
if (isValid(password)) {
System.out.println ("That is a valid string onto stage 2.");
}
else
{
System.out.println ("That is a invalid string. Try again.");
}
}
First of all, your isValid function never returns true, even the case that user enters a password that is greater than 6 characters. So you should update your method like that:
public static boolean isValid(String password) {
if (password.length() < 6) {
return false;
} else {
char c;
for (int i = 0; i < password.length() - 1; i++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (Character.isDigit(c)) {
return false;
}
}
}
return true;
}
Then, you can take the user input in a do-while loop. So if the password is invalid it will keep asking. Here is your updated main method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
{
String password;
do {
System.out.print("Please enter a string that is greater than 6 characters long. ");
password = input.next();
if (isValid(password)) {
System.out.println("That is a valid string onto stage 2.");
} else {
System.out.println("That is a invalid string. Try again.");
}
}while (!isValid(password));
}
}

How do I make my code loop back to the beginning in Java?

I've read that I would need to put "continue" after an "if" statement, but every I tried this with my if statement and it states that "continue cannot be used outside of a loop."
Set it in the loop. EX:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true){
System.out.print("Enter a password: The password must have at least eight characters, only letters and digits, and at least two digits. ");
String s = input.nextLine();
if (thepassword(s)) {
System.out.println("Valid Password");
break;
} else {
System.out.println("Invalid Password");
}
}
}
See more : Java Break and Continute
Use an outer infinite loop with a lable, then break the loop using break loop_lable. Check until a valid input is made.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a password: The password must have at least eight characters, only letters and digits, and at least two digits. ");
loop:for(;;)
{
String s = input.nextLine();
if (thepassword(s))
{
System.out.println("Valid Password");
break loop;
}
else
{
System.out.println("Invalid Password");
continue loop;
}
}
input.close();
}
public static boolean thepassword(String password) {
boolean thepassword = true;
if (password.length() < 8) {
thepassword = false;
} else {
int totaldigits = 0;
for (int n = 0; n < password.length(); n++) {
if (thedigit(password.charAt(n)) || theletter(password.charAt(n))) {
if (thedigit(password.charAt(n))) {
totaldigits++;
}
} else {
thepassword = false;
break;
}
}
if (totaldigits < 2) {
thepassword = false;
}
}
return thepassword;
}
public static boolean theletter(char c) {
return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}
public static boolean thedigit(char c) {
return (c >= '0' && c <= '9');
}
}

Need help confirming password after validation

The main program should ask for a password that is 8 characters, 1 upper, 1 lower & 1 digit. Once passed requirements it should ask the user to re-enter the password and check that the two passwords match. I need help adding that section to my code. Currently, the code compiles with no problem.
import java.util.Scanner;
public class PassChecker2 {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
String inputPassword;
System.out.println(" Please enter your Password:");
inputPassword = input.next();
System.out.println(checkerPass(inputPassword));
System.out.println("");
//main(args);
}
public static boolean lenthgCk (String password) {
if (password.length() > 7) {
if(checkerPass(password)) {
return true;
}
}
else {
System.out.println("Password must be at least 8 characters long.");
return false;
}
return true;
}
public static boolean checkerPass (String password) {
boolean hasUpperCase = false;
boolean hasLowerCase = false;
boolean hasDigit = false;
char c;
for (int i = 0; i < password.length(); i++) {
c = password.charAt(i);
if(Character.isUpperCase(c)) {
hasUpperCase = true;
}
else if(Character.isLowerCase(c)) {
hasLowerCase = true;
}
else if(Character.isDigit(c)) {
hasDigit = true;
}
if(hasUpperCase && hasLowerCase && hasDigit) {
return true;
}
else {
System.out.println("Password is invalid must meet all requirements.");
return false;
}
}
return true;
}
}
Just input another string the same way you inputted the original password and check that they are both equal:
System.out.println(" Please confirm your Password:");
Stirng confirmPassword = input.next();
if (!confirmPassword.equals(inputPassword)) {
System.out.println("Passwords do not match");
// And possibly exit the program here?
}

While Loop Parsing Issue

I'm trying to give the user an infinite amount of inputs until they enter q. I'm using a while statement to run the program, but when the user tries to quit I get an error because the program would try and parse q as an integer. Any ideas on how I should change the structuring of this to prevent the error from occurring?
Scanner in = new Scanner(System.in);
System.out.println("What would you like your Fibonacci number to be?(enter q to quit)");
String value = in.next();
int trueValue;
while(!value.equalsIgnoreCase("q")) {
trueValue = Integer.parseInt(value);
Fibonacci userCase = new Fibonacci(trueValue);
System.out.println(userCase.calculateFibonacci(userCase.getCaseValue()));
System.out.println("Please enter another number.");
value = in.next();
trueValue = Integer.parseInt(value);
}
If it matters, here are the methods being called within the loop.
public int calculateFibonacci(int caseValue) {
if(caseValue == 0)
return 0;
else if(caseValue == 1)
return 1;
else
return calculateFibonacci(caseValue-1) + calculateFibonacci(caseValue-2);
}
public int getCaseValue()
{
return caseValue;
}
You can remove the last
trueValue = Integer.parseInt(value);
since you are already doing that at the start of the loop.
do{ getting the user value before checking } while(checking if it's ok);
/* https://stackoverflow.com/questions/40519580/trying-to-determine-if-a-string-is-an-integer */
private boolean isInteger(String str) {
if(str == null || str.trim().isEmpty()) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if(!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
public static String check(Scanner in) {
String value;
do {
System.out.println("Please enter a number or q to quit.");
value = in.next();
} while(!value.equalsIgnoreCase("q") && !isInteger(value));
return value;
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
String value = check(in);
while(!value.equalsIgnoreCase("q")) {
Fibonacci userCase = new Fibonacci(Integer.parseInt(value));
System.out.println(userCase.calculateFibonacci(userCase.getCaseValue()));
value = check(in);
}
in.close();
}

Does a method used in main method need its own class?

I am writing a code that checks password entries. The main method checks a secondary method and outputs a line depending on whether it's true or false. My problem is when I compile it gives expected class error for the second method, but if I try to use the same class as my main it gives duplicate class error. I didn't think I needed a second class. Anyone care to help me out?
import java.util.Scanner;
public class CheckPassword {
public static void main(String[] args) {
scanner input = new Scanner(System.in);
System.out.println("Enter a password");
password = input.nextLine();
if (check(password)) {
System.out.println("Valid Password");
}
else{
System.out.println("Invalid Password");
}
}
}
public class CheckPassword {
public static boolean check(String password) {
boolean check = true;
if(password.length() < 8) {
check = false;
}
int num = 0;
for(int x = 0; x < password.length(); x++) {
if(isLetter(password.charAt(x)) || isDigit(password.charAt(x))){
if(isDigit(password.charAt(x))){
num++;
if (num >=2){
check = true;
}
else{
check = false;
}
}
}
}
}
}
No need another class, but needed to static import isDigit and isLetter. I fixed your code:
import java.util.Scanner;
import static java.lang.Character.isDigit;
import static java.lang.Character.isLetter;
public class CheckPassword {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a password");
String password = input.nextLine();
if (check(password)) {
System.out.println("Valid Password");
}
else{
System.out.println("Invalid Password");
}
}
public static boolean check(String password) {
boolean check = true;
if(password.length() < 8) {
check = false;
}
int num = 0;
for(int x = 0; x < password.length(); x++) {
if(isLetter(password.charAt(x)) || isDigit(password.charAt(x))){
if(isDigit(password.charAt(x))){
num++;
if (num >=2){
check = true;
}
else{
check = false;
}
}
}
}
return check;
}
}

Categories