一、双分支
基本语法:
if(条件表达式) {
执行代码块1;
}
else {
执行代码块2;
}
二、入门练习
编写一个程序,可以输入人的年龄,如果该同志的年龄大于18岁,则输出"你年龄大于18,要对自己的行为负责,送入监狱",否则输出“小于18岁不追究”。
package demo02;
import java.util.Scanner;
public class Single {
public static void main(String[] args) {
int age ;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入你的年龄");
age = scanner.nextInt();
if (age > 18){
System.out.println("你年龄大于18,要对自己的行为负责,送入监狱");
} else {
System.out.println("小于18岁不追究");
}
}
}
三、流程图
四、练习 一
package demo02;
public class Test07 {
public static void main(String[] args) {
int x = 7;
int y = 4;
if (x > 5) {
if (y > 5) {
System.out.println(x + y);
}
System.out.println("老王来了");//输出
}else {
System.out.println("x=" + x);
}
}
}
练习二
编写程序,声明2个double型变量并赋值。判断第一个数大于10.0, 且第2个数小于20.0,打印两数之和。
package demo02;
public class Test08 {
public static void main(String[] args) {
double num1 = 11.0;
double num2 = 21.0;
if (num1 > 10.0 && num2 > 20.0) {
double num3 = num1 + num2;
System.out.println("num1+num2=" + num3);
}
}
}
练习三
定义两个变量int,判断者的和,是否能被3又能被5整除打印提示信息
package demo02;
public class Test09 {
public static void main(String[] args) {
int num1 = 10;
int num2 = 3;
int num3 = num1 + num2;
if (num3 % 3 == 0 && num3 % 5 == 0){
System.out.println("能被3和5整除");
} else {
System.out.println("不能被3和5整除");
}
}
}
练习四
判断一个年份是否是每年,闰年的条件是符合下面二者之(1)年份能被4整除,但不能被100整除; (2)能被400整除
package demo02;
public class Test10 {
public static void main(String[] args) {
int year = 2000;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0 ) {
System.out.println(year + "年是闰年");
} else {
System.out.println(year + "不是闰年");
}
}
}