Java 基础之流程控制

本文介绍了Java中的基本输入输出方法,如System.out.println()和System.out.printf(),以及如何使用Scanner从用户获取输入。接着,详细讲解了if语句的使用,包括不同类型的条件判断,如整型、浮点型和引用类型的比较。此外,还讨论了switch语句和各种类型的循环(while、do...while、for),以及break和continue在循环控制中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 输入输出

输入

System.out.print()		// 不换行输出
System.out.println()	// 换行输出

格式化输出

System.out.printf() 结合占位符输出想要的格式,常见占位符:

  • %d:格式化输出整数
  • %x:格式化输出十六进制整数
  • %f:格式化输出浮点数
  • %e:格式化输出科学计数法表示的浮点数
  • %s: 格式化字符串,不知道用什么占位符,都可以用 %s
// 保留两位有效小数
System.out.printf("%.2f", 2.678);   // 2.68
System.out.printf("Hello, %s", "rose!");    // Hello, rose!

输入

// Control.java
import java.util.Scanner;

public class Control {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);	 // 创建 Scanner 对象
        System.out.print("Input your name: ");
        String name = scanner.nextLine();	// 获取终端输入(字符串)
        System.out.print("Input your age: ");
        int age = scanner.nextInt();	// 获取终端输入(int 类型)
        System.out.printf("Hi, %s, you are %d\n", name, age);

    }
}

标准输入需要在终端编译并输入:

F:\JavaStudy\Source\Hello World>javac Control.java

F:\JavaStudy\Source\Hello World>java Control
Input your name: rose
Input your age: 18
Hi, rose, you are 18

注意:Scanner 对象会自动转换数据类型,无需手动转换!

2. if 语句

1、使用整型来作为判断条件:

// 不要使用 80 <= score < 90 
int score = 98;
if (score >= 90) {
    System.out.println("A");
} else if (score >= 80 & score < 90) {
    System.out.println("B");
} else if (score >= 70 & score < 80) {
    System.out.println("C");
} else if (score >= 60 & score < 70) {
    System.out.println("D");
} else {
    System.out.println("E");
}

2、浮点型作为判断条件:

// 与某个数值的差的绝对值小于某个很小的数
double x = 1 - 9.0 / 10;
if (Math.abs(x-0.1) < 0.00001) {
    System.out.println("x is 0.1");
} else {
    System.out.println("x is not 0.1");
}

浮点型应利用差值小于某个临界值来判断,而不是直接判断。


判断引用类型是否相等

  • ==:标准数据类型判断的是值是否相等,引用类型判断的是否为同一指向(即是否为同一对象)
  • 引用类型值是否相等:使用 equals()
 // 判断引用类型是否相等
String a = "love";
String b = "LOVE".toLowerCase(Locale.ROOT);
if (a == b) {
    System.out.println("a == b");   
} else {
    System.out.println("a != b");   // a != b
}

if (a.equals(b)) {
    System.out.println("a == b");   // a == b
} else {
    System.out.println("a != b");
}

使用短路语句避免 null 类型时编译错误:

// 若 a != null 为假则不会计算 a.equals(b),从而避免 NullPointerException
String a = null;
String b = "LOVE".toLowerCase(Locale.ROOT);
if (a != null && a.equals(b)) {
    System.out.println("a == b");
} else {
    System.out.println("a != b");   // a != b
}

3. switch 多重判断

switch 可以根据某个表达式的结果,分别去执行不同的分支。

  • 遇到 break 才会结束,切记不能忘记
  • 若没有满足的条件,可以定义 default,输出默认值
// switch 多重判断
int salary = 20000;
switch (salary){
    case 15000:
        System.out.printf("rose salary is %d", salary);
        break;
    case 18000:
        System.out.printf("lila salary is %d", salary);
        break;
    case 19000:
        System.out.printf("john salary is %d", salary);
        break;
    default:
        System.out.printf("My salary is %d", salary);
        break;
}

如果有几个case语句执行的是同一组语句块,可以这么写:

int salary = 20000;
switch (salary) {
    case 15000:
        System.out.printf("rose salary is %d", salary);
        break;
    case 18000:
    case 19000:
        System.out.printf("john salary is %d", salary);
        break;
    default:
        System.out.printf("My salary is %d", salary);
        break;
}

比较字符串:

// 比较字符串是比较值是否相等
String fruit = "apple";
switch (fruit) {
    case "apple":
        System.out.println("Selected apple");
        break;
    case "pear":
        System.out.println("Selected pear");
        break;
    case "mango":
        System.out.println("Selected mango");
        break;
    default:
        System.out.println("No fruit selected");
        break;
}

4. while 循环语句

基本格式:

while (条件表达式) {
     循环语句
}

计算 1+2+3+100

int n = 0;
int sum = 0;
while (n <= 100) {
    sum += n;
    //n += 1;
    n++;		// n 自增 1 ,上述两种方式都可以
}
System.out.println(sum);	// 5050

死循环:

int n = 1;
int sum = 0;
while (n > 0) {
    sum += n;
    n++;
}
System.out.println(sum);	// -1073741824
System.out.println(n);		// -2147483648

因为 int 有最大值,当 n++ 一值自增超出 int 范围就会意外退出循环。


do while 循环

do...while 循环至少会执行一次循环语句,再判断,而 while 循环线判断再执行循环语句:

do {
    执行循环语句
} while (条件表达式);

计算 1+2+3+100

int n = 1;
int sum = 0;
do {
    sum += n;
    n++;
} while (n <= 100);
System.out.println(sum);

5. for 循环

for (初始条件; 循环检测条件; 循环后更新计数器) {
    // 执行语句
}

计算 1+2+3+100

int sum = 0;
for (int n = 1; n <= 100; n++) {
    sum += n;
}
System.out.println(sum);

for 循环遍历数组:

int[] arr1 = {90, 92, 95, 97, 99};
for (int n = 0; n < arr1.length; n++){
    System.out.println(arr1[n]);
}

for each 循环

for each 循环比 for 循环更适合用来遍历数组:

// for each 循环
int[] arr1 = {90, 92, 95, 97, 99};
for (int n : arr1) {
    System.out.println(n);
}

注意:除了数组外,for each循环能够遍历所有“可迭代”的数据类型,包括ListMap等。

6. break 和 continue

  • break:退出循环,通常都是配合if语句使用
  • continue:退出当前(本次)循环

1、当 n==20 时退出循环:

int sum = 0;
for (int n = 1; n <= 100; n++) {
    sum += n;
    if (n == 20) {
        break;
    }
}
System.out.println(sum);	// 210

2、多层循环中使用 break 语句:

for (int i = 0; i <= 10; i++) {
    for (int j = 0; j <= 10; j++) {
        System.out.println("j ===> " + j);

        if (j == i) {
            break;		// 只会退出内存循环,然后重新回到外层循环继续循环
        }
    }
    System.out.println("内存循环退出!");
}

运行结果:

j ===> 0
内存循环退出!
j ===> 0
j ===> 1
内存循环退出!
j ===> 0
j ===> 1
j ===> 2
内存循环退出!
j ===> 0
j ===> 1
j ===> 2
j ===> 3
内存循环退出!
j ===> 0
j ===> 1
j ===> 2
j ===> 3
j ===> 4
内存循环退出!
j ===> 0
j ===> 1
j ===> 2
j ===> 3
j ===> 4
j ===> 5
内存循环退出!
j ===> 0
j ===> 1
j ===> 2
j ===> 3
j ===> 4
j ===> 5
j ===> 6
内存循环退出!
j ===> 0
j ===> 1
j ===> 2
j ===> 3
j ===> 4
j ===> 5
j ===> 6
j ===> 7
内存循环退出!
j ===> 0
j ===> 1
j ===> 2
j ===> 3
j ===> 4
j ===> 5
j ===> 6
j ===> 7
j ===> 8
内存循环退出!
j ===> 0
j ===> 1
j ===> 2
j ===> 3
j ===> 4
j ===> 5
j ===> 6
j ===> 7
j ===> 8
j ===> 9
内存循环退出!
j ===> 0
j ===> 1
j ===> 2
j ===> 3
j ===> 4
j ===> 5
j ===> 6
j ===> 7
j ===> 8
j ===> 9
j ===> 10
内存循环退出!

3、continue 语句:

int sum = 0;
for (int n = 1; n <= 10; n++) {
    // 当 n 为偶数时,跳出当前循环,继续下一次循环,因此计算的是  1+3+5+7+9 = 25
    if (n % 2 == 0) {
        continue;
    }
    sum += n;
}
System.out.println(sum);    // 25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风老魔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值