if分支语句

简单if分支语句

if分支语句:
if(exp1){
    command1;
}else{
    command2;
}
注:if一个花括号结束{},else一个花括号结束{};最后的else都可以省去包括嵌套的if分支语句

举例:
/**
输入一个数字,判断其转换为ASCII码后的字母大小写
*/
package test_java;
import java.util.Scanner;
public class Test13{
    public static void main(String[] args){
        System.out.println("请输入一个数: ");
        Scanner input = new Scanner(System.in);
        int num = input.nextInt();
        if(num>=65 && num <=90){
            System.out.println("输入的是大写字母: "+(char)num);
        }else{
            System.out.println("输入的是小写字母: "+(char)num);
        }
        //输入一个年份判断式闰年还是平年(能被4整除,但不能被100整除能被400整除)
        int year = input.nextInt();
        if(year%4==0 && year%100!=0 || year%400==0){
            System.out.println("是闰年");
        }else{
            System.out.println("是平年");
        }
    }
}

if分支嵌套语句

if分支嵌套语句:嵌套的就是else if(exp2)这个语句
if(exp1){
    command1;
}else if(exp2){
    command2;
}else if(exp3){
    command3;
}else{
    command4;
}

举例:
//给出一个百分制成绩,要求输出成绩等级A/B/C/D/E,90分以上输出A,80~89输出B,70~79输出C,60~69输出D,60以下输出E
package test_java;
import java.util.Scanner;
public class Test14{
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("请输入一个成绩:");
        int score = input.nextInt();
        if(score>=90){
            System.out.println("成绩为:A");
        }else if(score<=89 && score>=80){
            System.out.println("成绩为:B");
        }else if(score<=79 && score>=70){
            System.out.println("成绩为:C");
        }else if(score<=69 && score>=60){
            System.out.println("成绩为:D");
        }else{
            System.out.println("成绩为:E");
        }
    }
}

if分支嵌套语句2——多层嵌套

if分支多层嵌套
if(exp1){
    command1;
    if(exp2){
        command3;
    }else{
        command4;
    }
}else{
    command2;
    if(exp3){
        command5;
    }else{
        command6;
    }
}

举例:
/**
 * if分支嵌套语句2——多层嵌套
 */
package test_java;
import java.util.Scanner;
public class Test15{
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("今天的天气如何:1—晴天  2-阴天");
        int nu = input.nextInt();
        if(nu==1){
            System.out.println("天气很好,是逛街还是逛公园:1-逛街 2-逛公园");
            int nu1 = input.nextInt();
            if(nu1==1){
                System.out.println("逛街");
            }else if(nu1==2){
                System.out.println("逛公园");
            }
        }else if(nu==2){
            System.out.println("天气不好,是在家看电影还是打游戏:1-看电影 2-打游戏");
            int nu1 = input.nextInt();
            if(nu1==1){
                System.out.println("看电影");
            }else if(nu1==2){
                System.out.println("打游戏");
            }
        }
    }
}

你可能感兴趣的:(if分支语句)