Java学习Day05

本文详细介绍了Java编程中顺序结构、选择结构(if、else、if-else if-else)、嵌套if和switch结构的应用实例,涵盖从基本逻辑到复杂条件判断。通过实例演示了如何运用这些结构进行程序控制。
摘要由CSDN通过智能技术生成

顺序结构

  • 从上到下顺序执行。

在这里插入图片描述

选择结构

  • if单选择结构

在这里插入图片描述

实列:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("input:");
    String s = scan.nextLine();
    //equals 判断字符串是否相等
    if (s.equals("hello")){
        System.out.println(s);
    }
    System.out.println("end");
    scan.close();
}
  • if双选择结构

在这里插入图片描述

实例:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    //分数大于90及格,小于90不及格
    System.out.println("input score:");

    int score = scan.nextInt();
    if (score>90){
        System.out.println("及格");

    }else {
        System.out.println("不及格");
    }
    scan.close();
}

if多选择结构

在这里插入图片描述

实例:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.println("input score:");

    int score = scan.nextInt();
    if (score==100){
        System.out.println("满分!");

    }else if (score>=90&&score<100) {
        System.out.println("A");
    }else if (score>=60&&score<90) {
    System.out.println("B");
}else if (score<60&&score>=0) {
        System.out.println("不及格");
    }else {
        System.out.println("输入不合法!");
    }
    scan.close();
}

嵌套if结构

在这里插入图片描述

switch多选择结构

在这里插入图片描述

实例

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
    System.out.println("input your grade:");
    /*Scanner本身并不支持获取char类型的数据
    但是可以通过charAt()方法截取string的首位来获取char类型的数据
    charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。*/
char grade = scan.next().charAt(0);
switch (grade){
    //case穿透,不加break会返回之后的所有case包括default swith匹配具体的值
    case 'A':
        System.out.println("优秀");
        break;
    case 'B':
        System.out.println("良好");
        break;
    case 'C':
        System.out.println("一般");
        break;
    case 'D':
        System.out.println("及格");
        break;
    case 'E':
        System.out.println("再接再厉");
        break;
    default:
        System.out.println("未知参数");
}
scan.close();
}

循环结构

while循环

在这里插入图片描述

实例:

public static void main(String[] args) {
    //输出1~10
    int i = 0;
    while (i<10){
        i++;
        System.out.println(i);
    }
}
public static void main(String[] args) {
    //计算 1+2+3+。。1000
    int i = 0;
    int sum = 0;
    while (i<=1000){
        sum = sum + i;
        i++;
    }
    System.out.println(sum);
}

do…while循环

在这里插入图片描述

实例:

public static void main(String[] args) {
    int i = 0;
    int sum = 0;
    do{
        sum = sum + i;
        i++;
    }while(i<=100);
    System.out.println(sum);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值