1.基本使用
package com.yl.pdfdemo.day01;
/**
* @Author wfj
* @Date 2021/1/10
* @Description if else 结构的基本使用
* @Version 1.0
*/
public class IfTest {
public static void main(String[] args) {
/**
* 分支结构中的if-else(条件判断结构)
*
* 一、三种结构
* 如果条件表达式为true就执行里面的代码快
* 1、if (条件表达式) {
* 代码...
* }
* 2选1,如果表达式为true就执行if里面的代码块,否则执行else的代码块
* 2、if (条件表达式) {
* 代码...
* } else {
* 代码...
* }
* 多选1
* 3、if (条件表达式) {
* 代码...
* } else if (条件表达式) {
* 代码...
* }
* ...
* else {
* 代码...
* }
*/
int age = 10;
if (age >= 18) {
System.out.println("已成年");
}
if (age > 18) {
System.out.println("已成年");
} else {
System.out.println("未成年");
}
if (age > 0) {
System.out.println("输入的数据非法");
} else if (age < 18) {
System.out.println("未成年");
} else {
System.out.println("已成年");
}
//求三个数中最大的值
int num1 = 10,num2 = 20,num3 = -17;
int max;
if (num1 > num2 && num1 > num3) {
max = num1;
} else if (num2 > num1 && num2 > num3) {
max = num2;
} else {
max = num3;
}
System.out.println(max);
}
}
2.练习
package com.yl.pdfdemo.day01;
/**
* @Author wfj
* @Date 2021/1/10
* @Description if else 练习
* @Version 1.0
*/
import java.util.Scanner;
public class ifTest1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入小明的成绩:");
int grade = scanner.nextInt();
if (grade == 100) {
System.out.println("奖励一台电脑");
} else if (grade > 90){
System.out.println("奖励一部手机");
} else if (grade > 60 && grade < 90) {
System.out.println("奖励一个笔盒");
} else {
System.out.println("今晚做厅长");
}
//练习2: 输入三个数,并且从小到大输出
Scanner sc = new Scanner(System.in);
System.out.println("请输入三个整数");
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int num3 = sc.nextInt();
if (num1 > num2) {
if (num3 > num1) {
System.out.println(num2+","+num1+","+num3);
} else if (num3 < num2) {
System.out.println(num3+","+num2+","+num1);
} else {
System.out.println(num2+","+num3+","+num1);
}
} else {
if (num3 > num2) {
System.out.println(num1 + "," + num2 + "," + num3);
} else if (num3 < num1) {
System.out.println(num3 + "," + num1 +"," + num2);
} else {
System.out.println(num1 + "," + num3 + "," + num2);
}
}
}
}