双分支控制 IF else
if(条件表达式){
执行代码块1(条件表达式为真执行这里)为假这里不执行
}else{
执行代码块2(条件表达式为假执行这里)为真这里不执行
}
当条件表达式为真 执行代码块1 ,条件表达式为假则跳过执行代码块1 执行代码块2
if else练习
import java.util.Scanner;
public class If01{
public static void main(String[]args){
//了解if else
System.out.print("请输入年龄");
Scanner mysc = new Scanner(System.in);
int age = mysc.nextInt();
if (age>=18) {
System.out.print("已满18,坐牢");
}else{
System.out.print("未满18,从轻发落");
}
//练习一-定义两个double变量,判断第一个数大于10.0 且第二个数字小于20.0 就输出两者的和
Scanner mysc1 = new Scanner(System.in);
double d1 = mysc1.nextDouble();
double d2 = mysc1.nextDouble();
if (d1 > 10.0 & d2 <20.0) {
System.out.print(d1+d2);
}else{
System.out.print("不符合条件");
}
//练习二-定义两个int变量,判断二者的和,是否能被3和5整除,打印提示信息
Scanner mysc2 = new Scanner(System.in);
int i1 = mysc.nextInt();
int i2 = mysc.nextInt();
int i3=i1+i2;
int j1 = i3%3;
int j2 = i3%5;
if (j1==0&j2==0) {
System.out.print("可以被整除");
}else{
System.out.print("不能被整除i1余"+j1+"i2余"+j2);
}
//练习三-判断一个年份是否为闰年,闰年的条件为两者之一
// (1)年份能被4整除但不能被100整除
// (2)能被400整除
Scanner mysc3 = new Scanner(System.in);
int y1 = mysc3.nextInt();
if ((y1%4==0&&y1%100!=0)||y1%400==0) {
System.out.println(y1+"是闰年");
}else{
System.out.println(y1+"不是闰年");
}
mysc3.close();
}
}
注意点 练习三 当条件表达式一侧为另一个条件表达式时可以使用小括号圈起来化作一个整体
if ((y1%4== 0&&y1%100!=0)||y1%400== 0)