Как заставить программу печатать, если булева переменная имеет значение true? - PullRequest
0 голосов
/ 16 ноября 2018

Я знаю, что это кажется очень простым вопросом, но имейте в виду, я новичок в Java. Прикрепленный является моим исходным кодом, и в конце я пишу, и если заявление вывести «Пароль действителен», если переменная «действительный» является истинным. Код работает нормально, пока не достигнет этой точки, после чего вместо вывода «пароль действителен» он выходит из программы? Я посмотрел на многочисленные потоки переполнения стека, чтобы увидеть, как это можно решить, и большинство потоков предлагают, чтобы этот код работал. Любой совет будет принят во внимание. Спасибо

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;

}
}

Ответы [ 3 ]

0 голосов
/ 16 ноября 2018

Вы должны поставить все свои else детали, подобные этой, в скобках,

ex:

Вместо использования

else 
    System.out.println("Password should be within 7 to 10 characters in length.");  
    valid = false;  

Пожалуйста, используйте это следующим образом

else
{
  System.out.println("Password should be within 7 to 10 characters in length.");
  valid = false;
}

Вы должны сделать это для всех ваших else частей, и это должно работать.

Если вы используете другие без скобок, только первая строка, которая следует после else, будет внутри else.Вот ошибка, которую вы делаете здесь.Также вы можете улучшить свой код, удалив ненужные присваивания в false и true всегда, если внимательно посмотрите, как он будет выполняться

0 голосов
/ 16 ноября 2018

Проблема здесь в скобках за другим.Вы печатаете какое-то утверждение в else, а затем действительный флаг становится ложным независимо от того, является ли условие истинным или ложным.Кроме того, закройте сканер в конце.Кроме того, вам не нужно проверять, действительно ли == true, вы можете просто поместить его в условие if.Ваш код будет выглядеть как

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;

}

}

0 голосов
/ 16 ноября 2018

Ваши пункты else не содержат скобок, и поэтому вы много раз много раз устанавливаете для valid значение false. Кроме того, вы не хотите устанавливать valid обратно на true, если он не прошел тест. Исправление обеих этих проблем должно дать вам что-то вроде

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;
}
...