Java Basics-Control Statement Classification

Overview of control statements

The emergence of control statements can make our programs logical/organized, and we can use control statements to implement a "business".

 2.2 控制语句分3类:
 *     选择语句;
 *     循环语句;
 *     转向语句。
 *
 2.3 选择语句也可以叫做分支语句
 *     if语句
 *     switch语句
 *
 2.4 循环语句:主要循环反复的去执行某段特定的代码块
 *     for循环
 *     while循环
 *     do...while..循环
 *
 2.5 转向语句
 *     break
 *     continue
 *     return

if…else…conditional statement

  • The grammatical structure and operating principle of the if statement.
    The if statement is a branch statement, which can also be called a conditional statement.

The first way of writing

 第一种写法:if翻译为如果的意思,所以又叫条件语句。
 
    if(不是随便写的,必须是布尔类型,也就是说这里不是true就是false的表达式){
    
    
       java语句;
       java语句;
    }
    这里的一个大括号{
    
    }叫做一个分支。
              
 该语法的执行原理是:
    如果布尔表达式的结果是true,则执行大括号中的程序,否则大括号中代码不执行。

Insert image description here
Business needs:

需求:
   1.从键盘上接收一个人的年龄;
   2.年龄要求为[0-150],其他值表示非法,需要提示非法信息。
   3.根据人的年龄来动态的判断这个人属于生命中的哪个阶段?
      [0-5] 婴幼儿
      [6-10] 少儿
      [11-18] 少年
      [19-35] 青年
      [36-55] 中年
      [56-150] 老年
public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入年龄:");
        int age = scanner.nextInt();

        if(age < 0 || age > 150){
    
    
            System.out.println("对不起,年龄不合法");
        }else{
    
    
            if(age <=5 ){
    
    
                System.out.println("婴幼儿");
            }else if(age <= 10){
    
    
                System.out.println("少儿");
            }else if(age <= 18){
    
    
                System.out.println("少年");
            }else if(age <= 35){
    
    
                System.out.println("青年");
            }else if(age <= 55){
    
    
                System.out.println("中年");
            }else {
    
    
                System.out.println("老年");
            }
        }
    }

Insert image description here
Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/flytalei/article/details/132859344