Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch / case request with boolean

I'm trying to create a method which checks if the Login (username and password) has a minimum of 6 charakters.

To realize that I created this method public void checkLoginData(final String username, final String password). In that method, I create to booleans (user and pass), with those I can create 4 different boolean-chains:

  • user: true pass: true
  • user: false pass: true
  • user: false pass: false
  • user: true pass: false

Now I'd like to do a switch/case request for each of them, but I don't get how to realize that...

If you ask why I need the switch, I just think I need it, because I'd like to do for every of those 4 boolean-chains, that it does/show something diffrent. Also I'd like to do this in a sexy-java-way not with tousands of diffrent 'ifs' :P, Please help!

Here's the code of the method:

public void checkLoginData(final String username, final String password){

    boolean user, pass;

    if (username.length() < 6){
        user = false;
    }else {
        user = true;
    }

    if (password.length() < 6){
        pass = false;
    }else {
        pass = true;
    }

    boolean[] logindaten = {user, pass};



}

Thx for the help in Advance!

Best Regards safari

like image 422
safari Avatar asked Jan 13 '12 12:01

safari


People also ask

Can we use boolean in switch case?

The Switch Statement It cannot be boolean, float, double, or String. It also works with enumerated types and and a few special "wrapper" classes: Character, Byte, Short, and Integer.

How do you change a boolean from true to false?

Method 1: Using the logical NOT operator: The logical NOT operator in Boolean algebra is used to negate an expression or value. Using this operator on a true value would return false and using it on a false value would return true. This property can be used to toggle a boolean value.

What is boolean in Java?

A Boolean expression is a Java expression that returns a Boolean value: true or false .


1 Answers

If you really want a "sexy-java-way" (but that depends what you understand as such) you can do something like (Java 7 required):

boolean user, pass;

switch (user + "-" + pass) {
    case "false-false":
        ...
    case "false-true":
        ...
    case "true-false":
        ...
    case "true-true":
        ...
    default:
        throw new RuntimeException(
            "something strange happening here, user: " + user + ",pass: " + pass);
}

but I would prefer to do just 2 distinct checks each with his owns message, the message being joined for presentation. (and not sure if that could be considered "sexy-java-way", more like a 'workaround')

like image 56
user85421 Avatar answered Oct 07 '22 20:10

user85421