Sử dụng Thông cáo chuyển Đôi khi bạn viết một tầng nếu tuyên bố, tất cả các nếu báo cáo nhìn rất giống nhau, vì tất cả họ đều đánh giá một biểu thức giống hệt nhau. Sự khác biệt duy nhất là mỗi khi so sánh kết quả của biểu thức có giá trị khác nhau. | Using switch Statements Sometimes when you write a cascading if statement all the if statements look very similar because they all evaluate an identical expression. The only difference is that each if compares the result of the expression with a different value. For example if day 0 dayName Sunday else if day 1 dayName Monday else if day 2 dayName Tuesday else if day 3 . else dayName Unknown In these situations you can often rewrite the cascading if statement as a switch statement to make your program more efficient and more readable. Understanding switch Statement Syntax The syntax of a switch statement is as follows switch case and default are keywords switch controllingExpression case constantExpression statements break case constantExpression statements break . default statements break The controllingExpression is evaluated once and the statements below the case whose constantExpression value is equal to the result of the controllingExpression run as far as the break statement. The switch statement then finishes and the program continues at the first statement after the closing brace of the switch statement. If none of the constantExpression values are equal to the value of the controllingExpression the statements below the optional default label run. NOTE If the value of the controllingExpression does not match any of the case labels and there s no default label program execution continues with the first statement after the closing brace of the switch statement. For example you can rewrite the previous cascading if statement as the following switch statement switch day case 0 dayName Sunday break case 1 dayName Monday break case 2 dayName Tuesday break . default dayName Unknown break Following the switch Statement Rules The switch statement is very useful but unfortunately you can t always use it when you might like to. Any switch statement you write must adhere to the following rules You can use switch only on primitive data types such as int or string. With