if语句根据某个条件的判断结果,将程序的流程分为两个分支。
switch语句则将程序流程分为多个分支。
Scanner input = new Scanner(System.in);
int hand=input.nextInt();
if (hand==0)
System.out.println("石头");
else if(hand==1)
System.out.println("剪刀");
else if(hand==2)
System.out.println("布");
相比于if语句switch语句更简洁
Scanner input = new Scanner(System.in);
int hand = input.nextInt();
switch (hand) {
case 0:
System.out.println("石头"); break;
case 1:
System.out.println("剪刀"); break;
case 2:
System.out.println("布"); break;
switch语句的语法结构图
if语句与switch语句的共同点是对程序流程进行分支,这两种语句统称为选择语句。
switch语句中的break语句被执行时,switch语句的执行将会终止。
所谓表达式,就是"变量","常量","通过运算符将变量和常量连接起来的式子"。
如果通过某个单一表达式的值将程序流程进行分支,最好使用switch语句。分支跳转的位置是标签。如果没有与控制表达式的值相等的标签,则跳转到default标签。