© Ron Dai 2019
R. DaiLearn Java with Mathhttps://doi.org/10.1007/978-1-4842-5209-3_18

18. Conditional Statements

Ron Dai1 
(1)
Seattle, WA, USA
 

How do you identify and express the bigger number between the two numbers, x and y?

Math: Hypothesis and Conclusion

In a mathematical formula, we have to introduce the absolute sign to form an expression:

The bigger number between x and y ../images/485723_1_En_18_Chapter/485723_1_En_18_Figa_HTML.gif $$ frac{left(mathbf{x}+mathbf{y}
ight)+mid mathbf{x}hbox{--} mathbf{y}mid }{mathbf{2}} $$

Recall the if/else structure:
if (x >= y) {
       // x is the bigger number
} else {
       // y is the bigger number
}

It is very straightforward and fairly easy to read!

The if/else structure follows a common experimentation of hypothesis-to-conclusion.
       if (<Hypothesis>) {
              <Conclusion>
       } else {              // the hypothesis is NOT valid
              <Different conclusion>
       }

The <Hypothesis> part needs to be a Boolean value, which may contain one variable or multiple variables in a math expression.

There are several types of structures for the conditional statements (some you’ve seen, some that will be new to you).
  • Simple if, or if/else clause.

  • A little more complicated if/else if ladder.

    if (...) {
           ......
    } else if (...) {
           ......
    } else if (...) {
           ......
    } else {
           ......
    }
  • Nested if/else statement.

    if (...) {
           ......
    } else {
           if (...) {
                  ......
           } else {
                  ......       ......
           }
    }

The final pattern is used to implement a tree-like structure. It will depend on the type of problems we solve when we decide which pattern to use.

Example

Is there anything wrong with the following block of code?
       if (i > 50) {
              <do something...>
       } else if (i > 100) {
              <do something...>
       } else {
              <do something...>
       }

Answer

When i <= 50, it will never be i > 100, so the else if branch in the middle is actually a dead path. An easy correction should be to just exchange the position of “50” and “100” in the code. And pay attention to this, when it says else if (i > 50) {...} in the following code block, it actually means 50 < i <= 100.
       if (i > 100) {
              <do something...>
       } else if (i > 50) {
              <do something...>
       } else {
              <do something...>
       }

Example

Create a method to map a student’s grades (0 to 100 integers) to a standard GPA score.

Answer

The first solution (v0) uses several if clauses. The problem is, for example, when the marks are 69, it has to execute all four if clauses . This is not an efficient approach.
       public static char getGpaScore_v0(int points) {
              if (points > 89) {
                     return 'A';
              }
              if (points < 90 && points > 79)       {
                     return 'B';
              }
              if (points < 80 && points > 69)       {
                     return 'C';
              }
              if (points < 70 && points > 64)       {
                     return 'D';
              }
              // if (points < 65) <-- this line can be omitted
              return 'F';
       }
The second solution (v1) utilizes a nested "if / else" statement. It solves the problem observed from an earlier version - v0.
       public static char getGpaScore_v1(int points) {
              if (points > 89) {
                     return 'A';
              } else {
                     if (points > 79) {
                            return 'B';
                     } else {
                            if (points > 69) {
                                   return 'C';
                            } else {
                                   if (points > 64) {
                                          return 'D';
                                   } else {
                                          return 'F';
                                   }
                            }
                     }
              }
       }
To provide better readability into the code structure, the third solution (v2) is introduced as shown.
       /*
        * 90 to 100 --- A
        * 80 to 89        --- B
        * 70 to 79        --- C
        * 65 to 69  --- D
        * below 65  --- F
        */
       public static char getGpaScore_v2(int points) {
              if (points > 89) {
                     return 'A';
              } else if (points > 79) {
                     return 'B';
              } else if (points > 69) {
                     return 'C';
              } else if (points > 64) {
                     return 'D';
              } else {
                     return 'F';
              }
       }

Math: Quadrants

On the Cartesian coordinate system, a quadrant is determined by whether the x and y coordinates are positive or negative numbers. There are four quadrants, separated by the x-axis and the y-axis. Specifically, all the points (x > 0, y > 0) belong to quadrant I (or 1st quadrant); all the points (x < 0, y > 0) belong to quadrant II (or 2nd quadrant); all the points (x < 0, y < 0) belong to quadrant III (or 3rd quadrant); and all the points (x > 0, y < 0) belong to quadrant IV (or 4th quadrant)

Example

Can you write a method to identify which quadrant on the coordinate system that any given point (x, y) belongs to? Both x and y are real numbers. If a point falls on the x-axis or the y-axis, then the method should return 0.

Answer

There are two variables, x and y, in this example. Define x and y as float type of numbers. Do case work analysis as shown below:

Case 1: When a point falls on either x-axis or y-axis ../images/485723_1_En_18_Chapter/485723_1_En_18_Figa_HTML.gif y = 0 or x = 0

Case 2: When a point falls in the 1st quadrant ../images/485723_1_En_18_Chapter/485723_1_En_18_Figa_HTML.gif x > 0 and y > 0

Case 3: When a point falls in the 2nd quadrant ../images/485723_1_En_18_Chapter/485723_1_En_18_Figa_HTML.gif x < 0 and y > 0

Case 4: When a point falls in the 3rd quadrant ../images/485723_1_En_18_Chapter/485723_1_En_18_Figa_HTML.gif x < 0 and y < 0

Case 5: When a point falls in the 4th quadrant ../images/485723_1_En_18_Chapter/485723_1_En_18_Figa_HTML.gif x > 0 and y < 0

Combining case 2 and case 5 to a category of x > 0, case 3 and case 4 to a category of x < 0 produces a code structure as:
       private static int quadrant(float x, float y) {
              if (x == 0 || y == 0) {
                     return 0;
              }
              else if (x > 0)              // x > 0 and y <> 0
              {
                     if (y > 0) {
                            return 1;
                     }
                     return 4;
              }
              else                         // x < 0 and y <> 0
              {
                     if (y > 0) {
                            return 2;
                     }
                     return 3;
              }
       }

It uses float to hold x and y values, although it could also use double to do so. Both float and double are numeric data types that are used for storing floating-point numbers. The double type requires twice as much space as the float type, as every float type of data is represented in 32 bits while one double type of data uses 64 bits

Ternary Operator

Java enables you to assign a value directly from a Boolean expression (true or false). This is called a ternary operator. For example:
       int a, b, max;
       max = a < b? b : a;

This implies, when a < b, max = b; otherwise max = a.

This syntax saves an if/else statement. For example, we may use the following method to get an absolute value:
       public int getAbsolutionValue(int a) {
              if (a < 0) {
                     return -a;
              }
              else {
                     Return a;
              }
       }
But by using the ternary operator, we will get it done by one line of code:
       a = a < 0 ? -a : a;

Problems

  1. 1.
    Please rewrite the code as below to improve its logic and readability (num is an integer value).
           if (num < 10 && num > 0) {
                  System.out.println("It's an one digit number");
           }
           else if (num < 100 && num > 9) {
                  System.out.println("It's a two digit number");
           }
           else if (num < 1000 && num > 99) {
                  System.out.println("It's a three digit number");
           }
           else if (num < 10000 && num > 999) {
                  System.out.println("It's a four digit number");
           }
           else {
                  System.out.println("The number is not between 1 & 9999");
           }
     
  2. 2.
    Take the following three if statements:
    if (a == 0 && b == 0) {...}
    if (a == 0 && b != 0) {...}
    if (a != 0 && b != 0) {...}

    Please simplify the code logic and combine them together.

     
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.63.87