Friday, March 9, 2018

Conditional Logic in java


Before we see Conditional Logics lets first see the Previous topics in the series of tutorials

Now we’ve been running a lot of programs since I started these tutorials. That should be… a few weeks ago? Six, maybe? I’m not exactly sure. What I am sure of is that by now you’re becoming comfortable with Java programming, and you’ve probably made a few small programs of your own initiative. (If you haven’t been doing this, then you probably should start doing so. It’s great programming practice).
Since we started these tutorials… six…seven weeks ago…that’s not important right now…we’ve only being working with one form of programming called Sequential Programming. Sequential Programming is basically when the code runs every line one by one, from top to bottom. It’s a very linear form of programming, and it is built to complete a particular task, and get one particular set of results.
Of course, not all programs work sequentially. You might often want a code to only do something when another thing as happened (when a condition is met). This is done with Selective Programming. At other times, you might want your code to do something more than once until some other conditions are met. This is done with Iterative Programming.
For the sake of this tutorial, we’re going to deal strictly with Selective Programming.
Selective Programming/Conditional Logic
Conditional Logic consists mainly of the use of IF statements. An if statement is basically saying that if this is true, or this is false, then this should happen OR if this is greater than this and less than this, then this is equal to that. (That should be not confusing at all).
The standard structure of IF statements in Java (and most other languages) is this:


if(condition) {
     //code
}

Let’s take a quick example. Open a new project or class and type this down:


boolean answer = true;
 if (answer) {
   System.out.println("The answer is true");
}

Run it and your code should give you this:
Okay, if we’re okay with that, let’s do a walkthrough. We started by creating a Boolean value named answer (remember from one of our last tutorial, we said that Boolean data types saved only two values: true or false). In this case, we saved the value true into the Boolean. We then proceeded to write an IF statement, we put that answer mist be equal to true in the conditions bracket. In the curly brackets, which is where our actual program goes, there’s a print statement, that is set to print to “The answer is true” on the output window.
All that is computer for: “If the answer is true, then tell us that the answer is true.”
You know when you’re playing a game, and when you make a particular decision, like moving left, and something happens, like a boulder falls on you and kills you. Yeah, it uses this basic concept. You could think of the coding like this (don’t type this out):

boolean turnLeft, boulderfall, die;
 if (turnLeft) {
    boulderfall = true;
 }
 if (boulderfall) {
    die = true;
}
Again, this is basically saying that if you turn left, a boulder will fall on you, and you will die. Note that the default value of Boolean is false, so it won’t be true until you set that it’s true. Also, you can put an IF statement after your previous statement. You can even put an IF statement inside an IF statement. This is called a Nested IF.
Now, change the answer variable from true to false, and run it again. When you’re done running it, and can see the output window, you probably ask yourself “What? Why didn’t anything print out?”.
 If you’re asking that question, then your output window probably looks like this:




And the reason there was nothing printed out is because there was nothing to tell the system to print out a message if the answer was true. In fact, there was nothing to tell the system what to do if the answer was true. If you want to do this, you could just add another IF statement.
OR
…you could use a form of conditional logic called…

IF…ELSE Statements

The basic concept of this is: If the answer is true, then tell us it’s true, if not, tell us it’s false. The standard structure of an IF…ELSE is this:

if(condition) {
   //code
}
else {
  //code
}
If you’re wondering why the else doesn’t need a condition, think of it like a last resort. If all the other conditions aren’t met, then the computer just has to do it. Now add this to your code (the answer variable should stay false:

else{
  System.out.println("The answer is not true");
}
Your code should now look like this:


Run it, and you should get the desired result.
Let’s try this out with integer values this time, but before we do this, we’ll have to take a quick look at some conditional operators (also called relational operators, these are the symbols that relate two values to each other):

<  Less Than
>  Greater Than
<= Less Than or Equal to
>= Greater Than or Equal to
&& AND
|| OR
== Equals to/Has a value of
! NOT
I’m sure these are quite self-explanatory. If there’re those who still don’t understand, It’ll all be clear in the next example. What we’ll be making is a programming that scans your age, and tells you if you’re over eighteen or under eighteen. Now, comment out everything and write this out.


     int age = 17;
        if (age < 18){
            System.out.println("You're underaged");
        }
        else{
            System.out.println("You're an adult");
        }

Now, this says: “If the age is under eighteen, then say that the user is underaged. If it’s not (i.e. if it’s 18 and above), then the user is an adult. Now before running it, look at the code. What do you think the result will be? Is it the same as the output in the picture below?


Try changing up the age variable. Make it 21, then 15, then 0, then 68; or something like that. But what if we want to put more conditions, since the IF…ELSE can only take one condition at a time. For example, what if we want a code that will tell if you’re a child when you enter a value within a particular age bracket, then it will tell you you’re an adult if you enter within another age bracket.
Well, you can enable the computer to make more than one of such decisions, with the use of…

IF…ELSE IF Statements

The standard structure for this is:

if(condition) {
  //code
}
else if (condition) {
  //code
}
else if(condition) {
  //code
}
else{
  //code
}
Depending on your code, an IF…ELSE IF can be as long as it needs to be, and can even end with an ELSE, as the default if none of the other conditions are met. Now, delete everything you’ve written and put this:

Now, the first IF will only run if ‘age’ is less than 13. The second IF, or the ELSE IF, contains two conditions: if age is greater than or equal to 13, and if it is less than or equal to 17. The presence of the double ampersand (&&) which means ‘and’, tells the computer not to run that programme unless both of those conditions are met. If I changed it to this (||) which means ‘or’, the code will run if at least one of the conditions are met.



The third IF says that the code should be run, only if the age is equal to 18 (note the double equal signs. I’ve made that mistake too many times). The last one is just another variation of the second IF, the only difference being the change of values to 19 and 35, the age bracket of adults according to the code. Then there’s the default else; if the input doesn’t meet the conditions, then the user must be old.
Switch up the value of age and run it. Then try modifying the conditions based on your definitions of an adult and a child (people have different opinions of which age determines an adult).

SWITCH STATEMENTS

Called Select Case, for those familiar with Visual Basic, this is another form of Selective Programming. It gives the option to test for a particular range of values, and it’s easier than writing long complex IF…ELSE statements. This is the basic structure:

switch (variable) {
case value:
 //code;
 break;
   default:
 //code;
 break;
}
Let’s take an example. Comment out everything except the variable age and write out this code







Bow every switch statement starts with the keyword switch, followed by brackets. In the brackets, you put in the name of the variable you want to test (in this case, it’s age). You then put curly brackets, and write case, then a value (like 17 for example). After a colon, you put the code you want to be executed when that condition is met. After that is the keyword break, which simply ends that statement.

What this is simply saying is: If age is 17, the do that. Or if it’s 18, then do something else. The keyword default works the same way as an ELSE, in the sense that it only runs when all the other requirements aren’t met.

Run it and you should get this:



Now, I think that’s enough for Conditional Logic, now it’s time to wrap this post up. I’d advise that you build on what we’ve done today. Try using my lessons on user input to make the IF statements more interactive. Also, experiment with other data types.

NB: Strings don’t use the same relationship operators as integers. Instead of this:

if (name == “Daniel”) {

…use this:

if (name.equal(“Daniel”) {

Next week, we’re going to be talking about Loops. We’ll be picking up the pace a bit, so try to keep up.



If you liked the article please share it with your friends and colleagues. 



Happy Learning 

Thanks for reading





0 comments:

Post a Comment