前言
判断与循环
文章目录
一、if 语句
1. 基本 if-else 形式
import java.util.Scanner;
public class Main
{
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
if (a > 5) {
System.out.printf("%d 大于 5", a);
} else {
System.out.printf("%d 小于 5", a);
}
}
2. 简写方式
- 省略 else 语句
import java.util.Scanner; public class Main { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); if (a > 5) { System.out.printf("%d is big", a); } }
- 省略 { }
import java.util.Scanner; public class Main { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); if (a > 5) System.out.printf("%d is big", a); else System.out.printf("%d is small", a); }
3. 嵌套 if-else
import java.util.Scanner;
public class Main
{
Scanner sc = new Scanner(System.in);
int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();
if (a > b) {
if (a > c)
System.out.prinln(a);
else
System.out.println(c);
} else {
if (b > c)
System.out.println(b);
else
System.out.println(c);
}
}
4. 连写 if-else
- 用来判断某一个值属于哪种情况
- 本质还是 else 中写 if 语句
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int s = sc.nextInt();
if (s >= 90) {
System.out.println("A");
} else if (s >= 80) {
System.out.println("B");
} else if (s >= 60) {
System.out.println("C");
} else {
System.out.println("D");
}
}
}
5. 条件表达式
(1)a && b
:在满足 a 的情况下,同时需要满足 b;
(2)a || b
:a b 两种情况,至少满足一个即可;
(3)!
:非
import java.util.Scanner;
public class Main
{
Scanner sc = new Scanner(System.in);
int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();
if (a >= b && a >= c) // a最大的情况
System.out.println(a);
else if (b >= a && b >= c) // b最大的情况
System.out.println(b);
else
System.out.println(c); // c最大的情况
}
if (!(x > 10))
System.out.printf("%d 不大于 10", x);
二、循环语句
1. 为什么需要循环
- 生活中的很多逻辑需要进行重复操作。
2. 理解循环的关键
- 找到循环的内容;
- 代码的循环顺序;
3. 分类
1)while 循环
- 本质为循环版的 if 判断。区别在于 if 只判断一次(如果成立,就执行判断内容,不成立就退出);while 是判断多次;
2)for 循环
- 基本结构
for (init-statement; condition; expression) {
statement
}
- 其它结构
init-statement可以定义多个变量
expression也可以修改多个变量
for (int i = 1, j = 10; i < j; i ++, j -- ) {
sum += i * j;
}
- 多层循环
4. 跳转语句
1) break
- 提前从循环中退出,一般与 if 语句搭配;
2)continue
- 直接跳到当前循环体的结尾;