4.2 More branches with if and else

The code

Before we proceed with today’s code. I assume you have already added an age variable in our Kid class. For convenience purpose, I assume it is public. If not, please add that public Integer age into your Kid class first. Now let’s reopen our Util class. Util class is defined in our previous post: 3.4 Pass by value and pass by reference .


public class Util 
{
    public static void educateKid(Kid k)
    {
        if(k.age < 3) 
        {
            System.debug('Play toys with the baby');
        }
        else if(k.age < 6)
        {
            System.debug('Teach some basic reading');
        }
        else if(k.age < 12)
        {
            System.debug('Let us learn some math.');
        }
        else if(k.age < 18)
        {
            System.debug('Teach some logical thinking');
        }
        else 
        {
            System.debug('Focus on the professional stuffs');
        }
    }
    //...
}

A bit explanation

Today’s grammar is nothing new. But just give you an brief idea on how you can use a list of if/else if/else to switch between all the options. It is pretty easy. But make sure you know how to use them in actual programming.

Exercise

In Commodity class, define a method. If the price is over 200 dollars, give 50% discount. If it is more than 100, 30% discount. Otherwise, no discount. Return the calculated price.

Next Post

4.3 Nested if statements

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *