By errors I mean errors in result.
PHP Code:
class Testing
{
public static void main(String[] args)
{
int foo = 20, bar = 0;
if (foo > 15) bar = 100;
if (foo > 0) bar = 50;
System.out.println(bar);
}
}
Quote:
|
Originally Posted by Result
50
|
Compared to:
PHP Code:
class Testing
{
public static void main(String[] args)
{
int foo = 20, bar = 0;
if (foo > 15) bar = 100;
else if (foo > 0) bar = 50;
System.out.println(bar);
}
}
Quote:
|
Originally Posted by Result
100
|
I can see where the confusion came from, I should have chosen my words more carefully. My apologies for that, but just know that
I'm referring to errors in calculations produced by the compiler, not errors that would keep the code from compiling (of which would yield warnings).
When I think about it, I've never tried the above code in GScript, so I have no clue what results would be produced with the GScript compiler so it might work the same, in which case the first bit of the statement that I made would be false. Regardless, the rest holds its value. Whether GScript bypasses your need to use an else statement in the situation or not, you should always use else if when writing statements checking for different values of the same variable.
Quote:
Originally Posted by Inverness
Consecutive nested if statements are to be avoided without a good reason (can't think of one).
|
Well, combining all of your checks into one statement limits how specific the information that you return to the user can be. If you nest if statements, then you can add an else check to each if statement returning error messages to the user that specifies exactly what they did wrong, rather than a general message coming from a large check that tells the compiler that the user violated one of the checks in the statement.
In the case of the safe script in the first post, if devilsknite un-nests his if statements as you told him to, then he can't report error messages back to the player if they, say, try to withdraw money from the safe but are not in the array of allowed accounts, since every check would be in one if statement and if you violate any of the checks, then the same message would be sent back to the player regardless of which one you violated. In this case, nested if statements would be better in that you can communicate information back to the player more efficiently in the event that they violate separate parts of the checks.
Pseudocode (for the withdrawing bit):
PHP Code:
if player's account in allowed array
{
if withdraw amount > 0
{
//Do withdraw stuff
} else tell player they must withdraw a positive number that's greater than 0
} else tell player they're not allowed to withdraw money
Just an example of why you would nest if statements.