简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM