Home > Software engineering >  Strings || Case Sensitive
Strings || Case Sensitive

Time:11-23

Need to make a password program, where the user sets a password at the beginning and the password can be entered 3 times before the program is stopped. The program can not be case sensitive.

    public static void main(String[] args) 
{
    Scanner sc = new Scanner(System.in);
    int attempts = 3;
    String password = "";
    System.out.println("Please input your password.");
    Scanner stringScanner = new Scanner(System.in);
    String PASSWORD = stringScanner.next();
    while (attempts-- > 0 && !PASSWORD.equals(password)) //compares and then decrements
    {
        System.out.print("Enter your password: ");
        password = sc.nextLine();
        if (password.equals(PASSWORD)) 
            System.out.println("Access Granted");
        else 
            System.out.println("Incorrect. Number of attempts remaining: "   attempts);     
    }
        if (attempts < 1) {
            System.out.println("You have entered too many incorrect passwords, please try again later.");
        }
        else {
            System.out.println("Secret: Water is not Wet.");
            }
        }                               
    }

Program prints as expected, but is not case sensitive

CodePudding user response:

The first part of your question says The program can not be case sensitive while afterwards you are stating that Program prints as expected, but is not case sensitive, so it's a little difficult to understand what you want. But by looking at the code and seeing that it is doing a case-sensitive comparison, and that you are not happy with it's behavior, I'm guessing you want this to be a case-INsensitive comparison. In that case, you can use String#equalsIgnoreCase: !PASSWORD.equalsIgnoresCase(password)

CodePudding user response:

simply if you need not to consider the case sensitive just do password.equalIgnoreCase(PASSWORD) but if you need to be sure that both have same case sensitive you can just convert both variables to .toUpperCase before the comparison

  • Related