Unit 3 Selections

Github Code

Learning

  • Making the computer seem smart with IF and IF-ELSE selection statements based on Boolean variables and expressions.
  • Using Switch-Case.
  • Creating Random numbers.
  • Formatting output

The boolean Type and Operators

  • Often in a program you need to compare two values, such as whether i is greater than j.
  • Java provides six comparison operators (also known as relational operators) that can be used to compare two values.
  • The result of the comparison is a Boolean value: true or false.
  • boolean 1 Bit => Range= true/false

                        public class Main {
                            public static void main(String[] args) {
                                boolean b = (1 > 2);
                                System.out.println(b);
                                if(true){
                                    System.out.println("Welcome to IS147");
                                }
                            }
                          }
                                            
						

Boolean Example

Sample code on Github boolean code


                

Comparison Operators

If Statements


					        //boolean expression returns true or false
							if (boolean-expression) { 
								statement(s);
							  }
							  	  
						

					        int radius=5;
							if (radius >= 0) {
								area = radius * radius * PI;
								System.out.println("The area"     
								  + " for the circle of radius " 
								  + radius + " is " + area);
							  }
							  
							 
                            
						
						

Example of if


					  
						public class Main {
							public static void main(String[] args) {
							  int x = 20;
							  int y = 18;
							  if (x > y) {
								System.out.println("x is greater than y");
							  }  
							}
						  }
						  
					
					

If Condition

Note

The if/else Statement


						public class Ifelse {
							int number = 4;
						  
							public static void main(String[] args) {

								if (boolean-expression) { 
									statement(s)-for-the-true-case;
								  }
								  else {
									statement(s)-for-the-false-case;
								  }
								  
							}
						  }
						
						

if-else Example

Sample code on Github if else code


                public class Main{
                 public static void main(String[] args) {
                    int radius = 0;
                     double area;
                        if (radius > 0) {
                        area = radius * radius * 3.14159;
                        System.out.println("The area for the"
                             + "circle of radius " + radius + 
                            " is " + area);
                        }
                         else {
                         System.out.println("Negative input");
                        }
                    }
                }
                        
				

IF else video

Multiple Alternative if Statements

Multi-Way if-else Statements

Trace if-else statement

Trace if else via code

Github code

Challenge #1

Github code

The else clause matches the most recent if clause in the same block.

Challenge #2

  • Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: .
  • This statement prints B.

						public static void main(String[] args) {
                            public class Main {
                                public static void main(String[] args) {
                                    int i = 1;
                                    int j = 2;
                                    int k = 3;
                                    if (i > j)
                                        if (i > k)
                                            System.out.println("A");
                                        else
                                            System.out.println("B");
                                }
                            }
                        }                            
                            
                            

                        //Solution
                        public class Main {
                            public static void main(String[] args) {
                                int i = 1;
                                int j = 2;
                                int k = 3;
                                if (i > j) {
                                    if (i > k)
                                        System.out.println("A");
                                }
                                else
                                    System.out.println("B");
                            }
                        
                        }
                        
                    

Tip

Caution

Logical Operators

# Operator Name
1 ! not
2 && and
3 || or
4 ^ exclusive or

Truth Table for Operator ! not

Truth Table for Operator && and

Truth Table for Operator || or

Truth Table for Operator ^ exclusive or

Truth Table Examples

Truth Table examples

switch Statements

  • Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths.
  • A switch works with the byte, short, char, and int primitive data types
  • switch logic

							switch (status) {
								case 0:  compute taxes for single filers;
										 break;
								case 1:  compute taxes for married file jointly;
										 break;
								case 2:  compute taxes for married file separately;
										 break;
								case 3:  compute taxes for head of household;
										 break;
								default: System.out.println("Errors: invalid status");
										 System.exit(1);
							  }
							  
                            
                            

Switch Examples

Switch examples

switch Statement Flow Chart

Switch Using Lambda Expressions



                        public class Main {
                            public static void main(String[] args) {
                                String dayOfWeek = "Tuesday";
                                // Using lambda expressions with switch
                                switch (dayOfWeek) {
                                    case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
                                            -> System.out.println("Work day");
                                    case "Saturday", "Sunday" -> System.out.println("Weekend");
                                    default -> System.out.println("Invalid day");
                                }
                            }
                        }
                    
                           

Conditional Operator

  • Ternary operator the only operator that accepts three operands: booleanExpression ? expression1 : expression2
  • Unary operator
  • The unary operators require only one operand; e.g . + , - , ++, -- ,!
  • Conditional examples

Conditional Operator or ternary operator Logic


							(boolean-expression) ? exp1 : exp2

                           

Frequently-Used Specifiers

Specifier Output Example
%b a boolean true or false
%c a character 'a'
%d a decimal integer 200
%f a floating-point number 45.4600
%e a number in standard scientific notation 4.555e+01
%s a string "IS 147"

Examples Specifier

Github code

							

Unary Single Operand and Binary Two Operands


                        public class UnaryOperators {
                            public static void main(String[] args) {
                                int a = 10;
                                
                                // Unary plus and minus
                                System.out.println(+a);  // 10
                                System.out.println(-a);  // -10
                        
                                // Increment and Decrement Operators
                                System.out.println(++a);  // Pre-increment: 11
                                System.out.println(a++);  // Post-increment: 11 (prints before incrementing)
                                System.out.println(a);    // 12 (after post-increment)
                                
                                System.out.println(--a);  // Pre-decrement: 11
                                System.out.println(a--);  // Post-decrement: 11 (prints before decrementing)
                                System.out.println(a);    // 10 (after post-decrement)
                        
                                // Logical NOT
                                boolean flag = true;
                                System.out.println(!flag); // false
                            }
                        }
                        
                        public class BinaryOperators {
                            public static void main(String[] args) {
                                int x = 10, y = 5;
                        
                                // Arithmetic Operators
                                System.out.println("Addition: " + (x + y));   // 15
                                System.out.println("Subtraction: " + (x - y));// 5
                                System.out.println("Multiplication: " + (x * y)); // 50
                                System.out.println("Division: " + (x / y));   // 2
                                System.out.println("Modulus: " + (x % y));    // 0
                        
                                // Relational Operators
                                System.out.println(x > y);  // true
                                System.out.println(x < y);  // false
                                System.out.println(x == y); // false
                                System.out.println(x != y); // true
                        
                                // Logical Operators
                                System.out.println((x > y) && (x > 0)); // true
                                System.out.println((x < y) || (x > 0)); // true
                        
                                // Bitwise Operators
                                System.out.println(x & y); // 0 (Bitwise AND)
                                System.out.println(x | y); // 15 (Bitwise OR)
                                System.out.println(x ^ y); // 15 (Bitwise XOR)
                        
                                // Assignment Operators
                                x += y;  // x = x + y;
                                System.out.println(x); // 15
                            }
                        }
                        


                           

Examples

  • Applying the operator precedence and associativity rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1

The Random Class

  • The Random class is part of the java.util package
  • It provides methods that generate pseudorandom numbers
  • A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values
  • 
    							import java.util.Random
    							//Using Math class
    							//If you want to generate a number from 0 to 100 then your code would look like this:
    							int number1 = (int)(Math.random() * 101);
    							System.out.println (number1);
    							//Using Random class
    						   Random rand = new Random ();
    						   int dice = rand.nextInt(6)+1;  (0-5) + 1 = 1-6
    						   int dice = rand.nextFloat()*6 +1;  (0.0-0.999)*6+1
    						   int bottles = rand.nextInt(100);  (0-99)
    						  
    							
    							
    						 

Random Examples

Github code

							

The Math Class

  • The Math class is part of the java.lang package
  • The Math class contains methods that perform various mathematical functions
  • The methods of the Math class are static methods (also called class methods)
  • Static methods can be invoked through the class name – no object of the Math class is needed
  • 
    							value = Math.cos(90) + Math.sqrt(delta);
     							double circumference = diameter*Math.PI;
     							int dice= (int) ( Math.random()*6+1);
    
                                
    						 

Math Class Examples

Github code

							

Debugging

Logic errors are called bugs. The process of finding and correcting errors is called debugging. A common approach to debugging is to use a combination of methods to narrow down to the part of the program where the bug is located. You can hand-trace the program (i.e., catch errors by reading the program), or you can insert print statements in order to show the values of the variables or the execution flow of the program. This approach might work for a short, simple program. But for a large, complex program, the most effective approach for debugging is to use a debugger utility.

Debugger

Debugger is a program that facilitates debugging. You can use a debugger to

  • Execute a single statement at a time.
  • Trace into or stepping over a method.
  • Set breakpoints.
  • Display variables.
  • Display call stack.
  • Modify variables.

Assignment

Classwork