Java程序的流程控制

· Scanner接收

从键盘获取不同类型的变量
步骤

  1. 导包
import java.util,Scanner
  1. Scanner实例化
Scanner scanner = new Scanner(System.in)
  1. 调用Scanner类的相关方法,获取指定类型的变量;Scanner 类提供了多种方法来读取不同类型的输入数据:
  • 读取整数 (nextInt())
System.out.print("请输入一个整数:");
int number = scanner.nextInt();
System.out.println("该数为" + number);
  • 读取浮点数 (nextDouble())
System.out.print("Enter a floating-point number: ");
double number = scanner.nextDouble();
System.out.println("You entered: " + number);
  • 读取字符串 (nextLine())
System.out.print("Enter a line of text: ");
String line = scanner.nextLine();
System.out.println("You entered: " + line);

一、顺序结构

程序从上到下的逐行执行,中间没有任何跳转

二、分支结构

1.if-else语句

if(条件表达式){ //条件表达式结果为true或者false
	代码块;// 满足条件表达式执行的代码块
}
else if(条件表达式){// 同上
	代码块;
}

2.switch-case语句

switch(表达式){ //根据switch语句中表达式的值,加入case语句,直到遇见break;siwtch中只有byte、short、char、int、枚举、string类型
	case 常量: //case后只能声明常量
		执行语句;
		break;
	case 常量:
		执行语句;
		break;
	.........;
	default:
		执行语句;
		break;
}

三、循环结构

循环可以嵌套使用

1.for循环

for(初始化条件; 循环条件;迭代条件){
	循环体;
}

2.while循环

初始化条件;
while(循环条件){
	循环体;
	迭代条件;
}

3.do-while循环

初始化条件;
do{
	循环条件;
	迭代条件;
}while(循环体);

举例

eg:九九乘法表

public class NineNineTable {
    public static void main(String[] args) {
        for (int i = 1; i <= 9;i++){
            for (int j = i;j <= 9;j++){
                System.out.print(i + "*" + j + "=" + (i*j) + "\t");
            }
            System.out.println();
        }
    }
}

eg:输出100以内的质数

public class PrimeNumbers {
    public static void main(String[] args) {
        // 输出100以内的所有素数
        for (int i = 2; i <= 100; i++) {
            boolean isPrime = true;
            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                System.out.print(i + " ");
            }
        }
    }
}

注意

  • break和contiue的使用
    1.break 关键字:用于立即退出当前循环,跳过循环体中剩余的语句,并继续执行循环之后的代码。
public class BreakExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                break; // 当 i 等于 5 时,退出循环
            }
            System.out.println(i);
        }
        System.out.println("Loop ended.");
    }
}

2.continue 关键字:用于跳过当前循环迭代中的剩余语句,并立即开始下一次迭代。如果循环条件仍然为真,循环将继续执行。

public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                continue; // 当 i 等于 5 时,跳过当前迭代并开始下一次迭代
            }
            System.out.println(i);
        }
        System.out.println("Loop ended.");
    }
}
  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值