Is it wrong to put if / else inside another?

if() { }else { if (IsAlternateRow=='true') IsAlternateRow = 'false'; else IsAlternateRow = 'true'; } 

Can I place an if and else statement inside another expression?

+4
source share
9 answers

to try

 IsAlternateRow = !IsAlternateRow; 

(updated to show how it will look in your code)

 var IsAlternateRow = false; if(/* -- insert equation here -- */) { // do something } else { IsAlternateRow = !IsAlternateRow; } 
+5
source

Note. The question was re-marked as JavaScript after this answer was posted (it was originally about Java, so this answer is about Java).

In general, this is great to place if and else inside an else clause.

However, there are a few problems with your code. IsAlternateRow=='true' not syntactically valid.

  • If this is string comparison, you should use double quotes and .equals() ;
  • If this is a logical comparison, you'd better just do IsAlternateRow = !IsAlternateRow instead of all the nested if .
+8
source

return (IsAlternateRow.equals ('true'))? 'false': 'true'

+4
source

Yes, placing an if inside an else is a good practice, but in most cases using an else if is clearer and cleaner. For instance.

 if (test) { // Do something } else if (otherTest) { // Do something else } else { // Do a third thing } 

infact is short for

 if (test) { // Do something } else { if (otherTest) { // Do something else } else { // Do a third thing } } 

and in most cases they should compile almost identical programs.

Your sample code is not very clear and will not compile correctly, a clearer code example can help us help you.

+4
source

In general, I would say that to answer such questions, you should ask yourself,

Is it easy to read?

Incorrect if/else nested expressions aren’t scary, but as soon as you start inserting an ad, you should probably reorganize.

+3
source

This is good, but there are simpler ways to do what you do:

 IsAlternateRow = !IsAlternateRow 
+2
source

Yes, you can. If you want to evaluate the same object / variable several times, you could use the switch statement, but in many cases the task in a checkerboard pattern if will also do the task.

+1
source

To answer your question, yes, you can infinitely enclose if / else expressions. The code you provided will not be a problem. Although, given that you are talking about Java, I assume that if this pseudo-code does not give the desired result.

+1
source

The correct way to do this is:

 if() { } else if (IsAlternateRow=='true') { IsAlternateRow = 'false'; } else { IsAlternateRow = 'true'; } 
+1
source

Source: https://habr.com/ru/post/1347575/


All Articles