Java (Chapter 2.3) : Composite IF


For any type of consultation, query or doubt. You may contact to the following: (+91) 9804 436 193 debabrataguha20@gmail.com 
and join the group  https://www.facebook.com/groups/331231161093613/




Let’s take the “month-number” to “count of days” example once again like previous 2 chapters. If you missed that, I will suggest you to go through those 2 chapters first and then come here. Anyway the program was like below, user would enter “month-number” as input and he/she will get the number of days as output.


Input                    output                 why?

1                            31                          1 means January & there are 31 days in that month 
2                            28/29                     2 means February and we can have 28/29 days in Feb
3                            31                          3 means March, that’s why output is 31days
4                            30                          4 means April and April has 30 days


So the solution of this was something like below after the implementation of Nested-IF ..

if ( m <=12 )
{
            if ( m >= 1 )
            {
                        if ( m>= 2 )
                        {
                                    if ( m >= 3 )
                                    {
                                                if ( m >= 4 )
                                                {
                                                            if ( m >= 5 )
                                                            {
                                                                        // So on .. till month no. 12 
                                                            }
                                                            else
                                                            {
                                                                        System.out.println ( ” 30 days ” );
                                                            }
                                                }
                                                else
                                                {
                                                            System.out.println ( ” 31 days ” );
                                               
                                    }
                                    else
                                    {
                                                System.out.println ( ” 28/29 days ” );
                                    }
                        }
                        else
                        {
                                    System.out.println ( ” 31 days ” );
                        }
}
else
{
                        System.out.println ( ” Invalid month ” );
}
}
else
{
            System.out.println ( ” Invalid month ” );
}          



So this program is long enough, that we can not write here. Here we have written the code upto month “April” only. To make it short we can introduce some shortcuts to combine all the conditions. This shortcut can be applied by “&&” and “||”.

“&&” is called as “AND Operator”. It means if all the conditions are TRUE, then only the IF-statement will be declared as “TRUE”.

“||” is called as “OR operator”. It means if any of the conditions are TRUE inside the parent IF statement, the combined statement will be declared as “TRUE”.




Let’s directly jump into the coding to make it more clear.. We will now try to rewrite the previous program again with combining the conditions HAVING COMMON OUTPUT.

if ( m > 12 || m < 1)
{
System.out.println ( ” Invalid month ” );
}
else
{
            if ( m == 1  || m==3 || m==5 || m==7 || m==8 || m==10 || m==12)
            {
                        System.out.println ( ” 31 days ” );
            }
            else
            {
                        if ( m == 2)
                        {
                                    System.out.println ( ” 30 days ” );
                        }
                        else
                        {
                                    System.out.println ( ” 28/29 days ” );
                        }
            }
}


That means if the month is January or the month is March or the month is May  or so on.. the output will be 31.. Again focus on my statement, specially on the word “OR” because a single month input can not be January And March And May.. It can be 1 value at a time. So “OR” is the best operator to be used here to combine the conditions having common output.

So let us analyze the above program in more details.

Say if the input is 3 in the above program.. means m==3,

Then the combined answer of if ( m == 1  || m==3 || m==5 || m==7 || m==8 || m==10 || m==12)  will return TRUE as one of its child condition is returning TRUE.

Say if the input is 4 in the above program.. means m==4,

Then the combined answer of if ( m == 1  || m==3 || m==5 || m==7 || m==8 || m==10 || m==12)  will return FALSE as no child condition is returning TRUE.







Let’s take another example like below:

Question version 1.

User will get admission in a school next year if he/she has 80% attendance and 70% marks in practical and  60% marks in theory.

Solution:

class chapter2_program5
{
            public static void main (String args[])

{
Scanner sc=new Scanner(System.in);
int att ,pm, tm;
System.out.println(“Enter percentage of attendance”);
att=sc.nextInt();

System.out.println(“Enter marks in practical”);
pm=sc.nextInt();

System.out.println(“Enter marks in theory”);
tm=sc.nextInt();
if( att >=  80 && pm >= 70 && tm >= 60)
{
System.out.println(” you will get admission ”);
}
else
{
System.out.println(” you will not get admission ”);
}
}
}



Note: It is to be noted that here to get admission , students need to satisfy all the underlying conditions, that is why “AND” operator is used. If all the sub-conditions return TRUE, then only the Parent condition will return TRUE. Missing any of them will lead to ELSE statement.



Question version 2.

Say Government is making rules easier. Now anyone will get admission in a school if he/she has any of the following,

1.      80% attendance
2.      70% marks in practical
3.      60% marks in theory.


Solution (skipping the input lines):

if( att >=  80 || pm >= 70 || tm >= 60)
{
System.out.println(” you will get admission ”);
}
else
{
System.out.println(” you will not get admission ”);
}


Note: It is to be noted that to get admission , students need to satisfy any one underlying condition only, that is why “OR” operator is used. If any sub-condition returns TRUE, then also the Parent condition will return TRUE. Missing all of them only will lead to ELSE statement.

Another thing here to be highlighted that a good student who satisfies all the conditions will also get admission. Try to differentiate between the word “Atleast one condiotion” and “Exactly one condition”. As you have more knowledge on English Language than me, it would be easier for you to get the idea of “Atleast one”. So the student who will satisfy all the conditions will also get admitted.




Question version 3.


Government is now making rules in more trickier way. Now anyone will get admission in a school if he/she has 80% attendance. For the students having lesser attendance will get another chance if they will have marks more than 70% practical and 60% in theory


Solution :

if( att >= 80 || ( pm >= 70 && tm >= 60) )
{
System.out.println(” you will get admission ”);
}
else
{
System.out.println(” you will not get admission ”);
}


Note: inner bracket is very important here. If you do not put the extra set of bracket for ( pm > 70 && tm>60) , it mean java might understand the logic in some different way. For the condition, if( att > 80 || pm > 70 && tm>60 ) , java might think the logic is like , attendance should be greater than 80% or practical marks should be greater than 70%, but surely students have to get 60% in theory paper. It is a wrong interpretation by the java code then. So to confirm the implementation of correct logic, better to use brackets.





Now take another example from the last chapter of nested-if.

Percentage of attendance Remarks/Comments
91-100 “Superb !!”
75-90 “Good.. Try to be more frequent”
50-74 “Considering for the last time”
25-49 “ Guardian Call “
<=24 “ No need to give Exam “


Our solution was like below:

import java.util.*;
class chapter2_program4
{
            public static void main (String args[])

{
Scanner sc=new Scanner(System.in);
int att;
System.out.println(“Enter percentage of attendance”);
att=sc.nextInt();
if(att>100)
{
System.out.println(”Invalid attendance”);
}
else
{
            if ( att >= 91)
            {
System.out.println(” Superb !! ”);
                                    }
                                    else
                                    {
                                                if ( att >= 75 )
                                                {
                                                            System.out.println(” Good try to be more frequent”); 
                                                }
                                                else
                                                {
                                                            if ( att >= 50 )
                                                            {
                                                                        System.out.println(” Considering last time”);
                                                            }
                                                            else
                                                            {
                                                                        if ( att >= 25 )
                                                                       
                                                                                    System.out.println(” Guardian Call”);
                                                                        }
                                                                        else
                                                                        {
          System.out.println(”No need to give exam”);
                                                                        }
                                                           
                                                }
                                    }
}
}
}



We can rewrite the code again using && , ||


import java.util.*;

class chapter2_program5
{
            public static void main (String args[])

{
Scanner sc=new Scanner(System.in);
int att; 

System.out.println(“Enter percentage of attendance”);
att=sc.nextInt();

if(att > 100)
{
System.out.println(”Invalid attendance”);
}

if ( att >= 91 && att <=100 )
{
System.out.println(” Superb !! ”);
                        }
                        
if ( att >= 75 && att <=90 )
                        {
                                    System.out.println(” Good try to be more frequent”); 
                        }
            
if ( att >= 50 && att <= 74 )
                        {
                                    System.out.println(” Considering last time”);
                        }

                        if ( att >= 25 && att <= 49)
                       
                                    System.out.println(” Guardian Call”);
                        }
                        else
                        {
System.out.println(”No need to give exam”);
}
}
}



Do you think that the above code is correctly converted? If the input is given as 95, means att=95, then what will be the output?

Output of the above program would be

Superb
No need to give exam


Strange output. Right? It happened because of the independent IF blocks. In case of att =95, it will go through all the IF blocks separately and will throw the following status

So let us see what happened exactly in case of att=95


if(att>100)                               àreturns FALSE, No ELSE block, nothing will be printed 
if ( att >= 91 && att <=100 )  à returns TRUE and will print “Superb” 
if ( att >= 75 && att <=90 )    à returns FALSE, No ELSE block, nothing will be printed 
if ( att >= 50 && att <= 74 )   à returns FALSE, No ELSE block, nothing will be printed
if ( att >= 25 && att <= 49)    à returns FALSE, will go to the ELSE block and will print “no Need to give the exam”



It means the last ELSE block does not belong to other IF blocks.  It is only linked with the last independent IF block.

Ideally , the flow should be stopped after the first match itself. So it is always a best practice to put everything inside the Nested-IF to avoid this kind of unwanted errors. We will be ending this chapter with the correct code of Composite IF.



import java.util.*;

class chapter2_program5
{
            public static void main (String args[])

{
Scanner sc=new Scanner(System.in);
int att;
System.out.println(“Enter percentage of attendance”);
att=sc.nextInt();
if(att>100)
{
System.out.println(”Invalid attendance”);
}
else
{
if ( att >= 91 && att <=100 )
{
System.out.println(” Superb !! ”);
                                    }
                                    else
                                    {
if ( att >= 75 && att <=90 )
                                                {
                                                            System.out.println(” Good try to be more frequent”); 
                                                }
                                                else
                                                {
if ( att >= 50 && att <= 74 )
                                                            {
                                                                        System.out.println(” Considering last time”);
                                                            }
                                                            else
                                                            {
                                                                        if ( att >= 25 && att <= 49)
                                                                       
                                                                                    System.out.println(” Guardian Call”);
                                                                        }
                                                                        else
                                                                        {
System.out.println(”No need to give exam”);
}
}
}
                                       }
                              }
               }
}

Comments

Popular posts from this blog

Java concepts Theory

About Myself ..