🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Week 3 Switches.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Transcript

The switch statement The switch statement • The if-else-if control structure can be used to test for multiple cases. • The if –else - if statement can become cumbersome if testing for multiple, specific conditions. • Java provides a special structure for this purpose. The switch control structure...

The switch statement The switch statement • The if-else-if control structure can be used to test for multiple cases. • The if –else - if statement can become cumbersome if testing for multiple, specific conditions. • Java provides a special structure for this purpose. The switch control structure is used when a variable is to be tested against multiple cases. switch example int choice; : //rest of code here : switch(choice) { case 1: System.out.print("option 1 chosen"); break; case 2: System.out.print("option 2 chosen"); break; //If this case executes switch ends case 3: System.out.print("option 3 chosen");; break; default: System.out.print("Invalid option!"); } //end switch here The switch statement The switch statement consists of - a switch expression, - a series of case clauses containing a constant, and - an optional default clause. A switch statement may be used when • a variable (int or char) is being checked for an exact match; • the check involves specific values of that variable, for example 'A', 'B‘, 10, 20, and not ranges like >39 • Java 7 allows use of String in switch statement The switch statement switch(variable) { case constant1: case constant2: case constant3: case constant4: default: statement(s); break; statement(s); break; statement(s); break; statement(s); break; statement(s); } There can be any number of case clauses. The switch statement switch(grade) { case 'A' : System.out.print("Excellent Student"); break; case 'B' : System.out.print("Good Student"); break; case 'C' : System.out.print(“Working Hard"); break; case 'D' : System.out.print("OK Student"); break; case 'E' : System.out.print("Weak Student"); break; default : System.out.print("Invalid grade entered"); } Ensure the switch statement is indented appropriately In the above example, the variable grade will be evaluated • if grade matches any of the case constants then the statement(s) in that case clause will be executed. Execution will continue until either a break is encountered or the end of the switch statement is encountered. • if grade does not match any of the case constants then the default statement(s) will be executed. How a switch statement operates • Evaluate the switch variable. • Check each case constant for a match to the switch variable and execute the statements until break encountered • If there is no case that matches the switch expression go to the default • If there is no default terminate the switch statement. • Terminate the switch statement when either a break is encountered or the end of the switch statement is encountered. default • The default is optional (like the else in an if/else). If it is present however, it should be placed last. • The default statement is equivalent to the else part of the if...else and if...else...if statements – it catches situations where none of the conditions are met. break; • Every branch of the switch should be terminated by a break statement. • The break is not mandatory, however, if the break; is not present, execution falls through to next branch, until end of switch is reached. – without the break the cases following the match will also be executed - it will not break out of the statement when required. Consider the code…. import java.util.Scanner; public class SwitchExample { public static void main(String[] args) { Scanner keyboardIn = new Scanner(System.in); char grade; // Character variable called grade System.out.print ("Enter student's grade: grade = keyboardIn.next().charAt(0); "); switch(grade) { case 'A' : System.out.print("Excellent Student"); break; case 'B' : System.out.print("Good Student"); break; case 'C' : System.out.print("Working Hard"); break; case 'D' : System.out.print("OK Student"); break; case 'E' : System.out.print("Weak Student"); break; default : System.out.print("Invalid grade entered"); }//end switch } //end main method } //end class What is output if ‘b’ is entered? Consider the code… • Invalid grade entered would be displayed as there is no match for b • Let’s look at how to solve this • Known as case sharing Multiple cases switch(grade) { case 'A': case 'a': System.out.print("Excellent Student"); break; case 'B': case 'b': System.out.print("Good Student"); break; case 'C': case 'c': System.out.print("Working Hard"); break; case 'D': case 'd': System.out.print("OK Student"); break; case 'E': case 'e': System.out.print("Weak Student"); break; default: System.out.print("Invalid grade entered"); }//end switch A program using else/if import java.util.Scanner; public class Timetable { public static void main(String[] args) { Scanner keyboardIn = new Scanner(System.in); char group; // Character variable called group System.out.println("****Lab Times**** "); System.out.print ("Enter your group: "); group = keyboardIn.next().charAt(0); //check tutorial group and display appropriate time if(group == 'A') { System.out.print("10.00 am"); //lab time for group A } else if(group == 'B') { System.out.print("1.00 pm"); //lab time for group B } else if(group == 'C') { System.out.print("11.00 am"); //lab time for group C } else { System.out.print("Invalid data entered"); //invalid data } } //end main method } //end class The same program using switch import java.util.Scanner; public class TimetableSwitch { public static void main(String[] args) { Scanner keyboardIn = new Scanner(System.in); char group; // Character variable called group System.out.println("****Lab Times**** "); System.out.print ("Enter your group: "); group = keyboardIn.next().charAt(0); //check tutorial group and display appropriate time switch(group) { case 'A':System.out.print("10.00 am"); //lab time for group A break; case 'B':System.out.print("1.00 pm"); //lab time for group B break; case 'C':System.out.print("11.00 am"); //lab time for group C break; default: System.out.print("Invalid data entered"); }//end switch } //end main method } //end class Allow for upper and lowercase letters using multiple cases import java.util.Scanner; public class TimetableSwitch { public static void main(String[] args) { Scanner keyboardIn = new Scanner(System.in); char group; // Character variable called group System.out.println("****Lab Times**** "); System.out.print ("Enter your group: "); group = keyboardIn.next().charAt(0); //check tutorial group and display appropriate time switch(group) { case 'A': case 'a': System.out.print("10.00 am"); //lab time for group A break; case 'B': case 'b':System.out.print("1.00 pm"); //lab time for group B break; case 'C': case 'c':System.out.print("11.00 am"); //lab time for group C break; default: System.out.print("Invalid data entered"); }//end switch } //end main method } //end class Limitations of switch • The switch is limited – can only be used with variables of type int or char and String objects (Java 7 introduced use of String) • Cannot be used to compare floating point values – Only one variable can be checked in a switch statement – The values in case clause must be constants – Can only be used to test for an exact match. • It cannot be used to test if value lies in a range case: < 2; // syntax error • Any switch statement can be rewritten as an if-elseif, but not every if-else-if can be rewritten as a switch. Rewrite using switch if(marriageStatus == 'S') { System.out.print("Single"); } else if(marriageStatus == 'M') { System.out.print ("Married"); } else if (marriageStatus == 'W') { System.out.print("Widowed"); } else { System.out.print("Invalid code"); } switch(marriageStatus) { case 'S':System.out.print("Single"); break; case 'M':System.out.print("Married"); break; case 'W':System.out.print("Widowed"); break; default:System.out.print("Invalid code"); } Rewrite using switch if(marriageStatus == 'S' || marriageStatus == 's') { System.out.print("Single"); } else if(marriageStatus == 'M' || marriageStatus == 'm') { System.out.print ("Married"); } else if(marriageStatus == 'W' || marriageStatus == 'w') { System.out.print("Widowed"); } else { System.out.print("Invalid code"); } switch(marriageStatus) { case 'S': case 's':System.out.print("Single"); break; case 'M': case 'm':System.out.print("Married"); break; case 'W': case 'w':System.out.print("Widowed"); break; default:System.out.print("Invalid code"); } Example using String in a switch String awardStr; System.out.print("Enter award[Distinction, Merit, Pass or Fail]: "); awardStr = keyboardIn.next(); //read in a string switch (awardStr) { case "distinction" : System.out.println("Result between 70-100."); break; case "merit" : System.out.println("Result between 55-69."); break; case "pass" : System.out.println("Result between 40-54."); break; case "fail" : System.out.println("Result between 0-39."); break; default: System.out.println("Invalid entry."); } //end switch This will only work properly when text is typed all lowercase Example using String in a switch String awardStr; System.out.print("Enter award[Distinction, Merit, Pass or Fail]: "); awardStr = keyboardIn.next(); //read in a string Converts string to lower switch (awardStr.toLowerCase()) case for comparison { case "distinction" : System.out.println("Result between 70-100."); break; case "merit" : System.out.println("Result between 55-69."); break; case "pass" : System.out.println("Result between 40-54."); break; case "fail" : System.out.println("Result between 0-39."); break; default: System.out.println("Invalid entry."); } //end switch This will work regardless of case of the string

Tags

java programming switch statement
Use Quizgecko on...
Browser
Browser