if else if与if语句嵌套
if else if语句和if语句嵌套是编程中常用的控制结构,用于根据不同的条件执行不同的代码块。下面列举了十个例子来说明这两种语句的用法。
1. 判断一个数字是否为正数、零或负数:
```
int num = 5;
if (num > 0) {
System.out.println("该数字是正数");
} else if (num == 0) {
System.out.println("该数字是零");
} else {
System.out.println("该数字是负数");
}
```
2. 根据用户的输入判断季节:
```
Scanner scanner = new Scanner(System.in);
System.out.println("请输入月份:");
if语句的嵌套例子模板int month = Int();
if (month >= 1 && month <= 3) {
System.out.println("当前是春季");
} else if (month >= 4 && month <= 6) {
System.out.println("当前是夏季");
} else if (month >= 7 && month <= 9) {
System.out.println("当前是秋季");
} else if (month >= 10 && month <= 12) {
System.out.println("当前是冬季");
} else {
System.out.println("输入的月份不合法");
}
```
3. 判断一个年份是否为闰年:
```
int year = 2020;
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println(year + "年是闰年");
} else {
System.out.println(year + "年不是闰年");
}
```
4. 判断一个字符是否为字母、数字或其他字符:
```
char ch = 'A';
if (ch >= 'a' && ch <= 'z') {
System.out.println(ch + "是小写字母");
} else if (ch >= 'A' && ch <= 'Z') {
System.out.println(ch + "是大写字母");
} else if (ch >= '0' && ch <= '9') {
System.out.println(ch + "是数字");
} else {
System.out.println(ch + "是其他字符");
}
```
5. 判断一个年龄段所属的人:
```
int age = 25;
if (age < 18) {
System.out.println("未成年人");
} else if (age >= 18 && age <= 60) {
System.out.println("成年人");
} else {
System.out.println("老年人");
}
```
6. 判断一个学生的成绩等级:
```
int score = 80;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 70) {
System.out.println("中等");
} else if (score >= 60) {
System.out.println("及格");
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论