if语句通常用来进行判断,有三种格式
第一种:
对输入的变量进行判断
if(关系表达式){ 语句体 }
代码示例
Scanner sc =new Scanner(System.in);
System.out.println("请输入你的酒量");
int wine=sc.nextInt();
//对酒量进行判断
if(wine>2){
System.out.println("酒量不错呦");
}
注意:如果对一个布尔类型的变量进行判断,不要用==号,直接把变量写在小括号中,这样写是为了避免将==和=写混。
代码示例:
boolean flag = false;
if(flag){
System.out.println("flag的值为false");
}
第二种:
两个条件进行判断
if(关系表达式){ 语句体1; }else{ 语句体2; }
代码示例:
//电影院座位问题
Scanner sc =new Scanner(System.in);
System.out.println("请输入你的票号");
int ticket=sc.nextInt();
if(ticket >=0 && ticket <=100){
if(ticket %2 ==1){
System.out.println("坐左边");
}else{
System.out.println("坐右边");
}
}
System.out.println("票号无效");
第三种:
多个条件进行判断
if(关系表达式){ 语句体1; }else if(关系表达式2){ 语句体2; } ... else{ 语句体 n+1; }
代码示例:
//分数奖励问题
Scanner sc =new Scanner(System.in);
System.out.println("请输入你的票号");
int score=sc.nextInt();
if(score >=0 && score<= 100){
if (score >= 95 && score <= 100) {
System.out.println("奖励自行车一辆");
} else if (score >= 80 && score <= 94) {
System.out.println("游乐场玩一天");
} else if (score >= 60 && score <= 80) {
System.out.println("变形金刚一个");
}
System.out.println("干一顿");
}
System.out.println("成绩不合法");
这就是if语句的三种格式,按照所给条件选择合适的语句。