what is the difference between
Scenario 1:
if (condition)
{
do something;
}
else
{
if(condition)
{
do something;
}
}
Scenario 2:
if (condition)
{
do something;
}
else if(condition)
{
do something;
}
Scenario 3:
if (condition)
{
}
else
{
do something;
}
question 1: I have seen 1st and 2nd scenarios in some tutorials why do u have to explicitly define the condition for else .? It would automatically go to else condition when if condition is false why do u have to again开发者_C百科 specify the condition ??
question 2:
What is the difference between scenario 1 and scenario 2 ??
The first and second are identical. After the else
you can either use a single statement or a block. In the first example you've used a block, and in the second you have used a single if
statement. Both do exactly the same thing.
The third is different because there are only two possible outcomes, but in the first two there are three possible outcomes (the third possibility is doing nothing at all if both conditions fail).
There is no difference between 1
and 2
.
The point of using else if
is that if neither condition is met, none of the code will be executed.
In each scenario, there should be two different conditions, named, for example, condition1 and condition2, not condition and condition.
Scenario 1 can also be cascaded with more than one else if {} clause as follows
if (condition1)
doAction1();
else if (condition2)
doAction2();
else if (condition3)
doAction3();
...
This can be useful in Java when the conditions involve tests such as string equality that cannot be put into a switch statement. Of course if you have too many of these, it's probably a sign that you're not factoring the code properly.
Conditions could not only be A or B, you know? They could be A or B or C... With
An example is better than 1000 words...
IF you knew the solution, you wouldn't have asked this question
ELSE IF you knew of stackoverflow, you could have asked this question here
ELSE you would have remained ignorant
:-)
In your case, you "activated" the second row... You are lucky!
Now... if someone truly wants 20 lines of explanation of if/else statements, of if with and withtout curly braces and the differences between else if and elseif (or elif), then I can write them... But I don't think they are truly necessary....
精彩评论