Anand Vasudevan
Anand Vasudevan

Reputation: 49

Find what fails in a if statement

I have the below code & want to use the condition that fails in my toast message. how do i do that without checking each if?

if(player1.isNullOrBlank() || player2.isNullOrBlank())
    Toast.makeText(this,"Please enter both player names",Toast.LENGTH_LONG).show()

Upvotes: 0

Views: 152

Answers (4)

gonutz
gonutz

Reputation: 5582

Just write the code. Do not overthink this. Just check what you have to check and provide good error messages. The || operator does not output a side-track variable to check or anything like that. Just write the code.

if (player1.isNullOrBlank() && player2.isNullOrBlank()) {
    Toast.makeText(this, "Please enter both player names", Toast.LENGTH_LONG).show()
} else if(player1.isNullOrBlank()) {
    Toast.makeText(this, "Please enter player name 1", Toast.LENGTH_LONG).show()
} else if(player2.isNullOrBlank()) {
    Toast.makeText(this, "Please enter player name 2", Toast.LENGTH_LONG).show()
}

Upvotes: -1

Damon Baker
Damon Baker

Reputation: 907

I would just use a when expression here since you're going to have to check each condition regardless.

val errorMessage -> when {
    player1.isNullOrBlank() && player2.isNullOrBlank() -> "Please enter a name for both players"
    player1.isNullOrBlank() -> "Please enter a name for Player 1"
    player2.isNullOrBlank() -> "Please enter a name for Player 2"
    else -> null
}

if (errorMessage != null) {
    Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show()
} else {
    // success condition
}

Another example, using also instead of an assignment.

when {
    player1.isNullOrBlank() && player2.isNullOrBlank() -> "Please enter a name for both players"
    player1.isNullOrBlank() -> "Please enter a name for Player 1"
    player2.isNullOrBlank() -> "Please enter a name for Player 2"
    else -> null
}?.also { errorMessage ->
    Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show()
}

Upvotes: 2

Stefan Zhelyazkov
Stefan Zhelyazkov

Reputation: 2981

Try something like this:

val nullPlayerNames = listOf("p1" to player1, "p2" to player2)
    .filter { (_, p) -> p.isNullOrBlank() }
    .joinToString(separator = ", ") { (tag, _) -> tag }
Toast.makeText(this, nullPlayerNames, Toast.LENGTH_LONG).show()

Upvotes: 0

Mike
Mike

Reputation: 1343

You can use Logs:

Log.e("Player 1 Status", player1.isNullOrBlank() + "");
Log.e("Player 2 Status", player2.isNullOrBlank() + "");

And check the Red Log in your LogCat when you run it.

Upvotes: 0

Related Questions