【JavaSE】Program logic control

Table of contents

【1】Concept

【2】Sequential structure

【3】Branch structure

【3.1】if statement

【3.2】switch statement

【4】Loop structure

【4.1】while loop

【4.2】for loop

【4.3】do while loop

【4.4】break keyword

【4.5】continue keyword

【5】Input and output

【5.1】Output to console

【5.2】Input from keyboard

【6】Guess the number game


【1】Concept

My past:

        Get up at 8:00 in the morning --> wash --> have breakfast --> go to class --> have lunch --> go to class --> exercise --> finish eating --> play with mobile phone --> sleep. Everyday life seems to be the same It's all so regular, doing everything in order, the future is bleak~~~

My past:

        Get up at 8:00 in the morning --> wash --> have breakfast --> go to class --> have lunch --> go to class --> exercise --> finish eating --> play with mobile phone --> sleep. Everyday life seems to be the same It's all so regular, doing everything in order, the future is bleak~~~

        Just working hard day after day , I feel fulfilled every day, and I see hope in life~~~

【2】Sequential structure

        The sequence structure is relatively simple, and is executed line by line in the order in which the code is written.

System.out.println("aaa");
System.out.println("bbb");
System.out.println("ccc");

// 运行结果
aaa
bbb
ccc

        If you adjust the writing order of the code, the execution order will also change.

System.out.println("aaa");
System.out.println("ccc");
System.out.println("bbb");

// 运行结果
aaa
ccc
bbb

【3】Branch structure

【3.1】if statement

  1. Grammar format 1

if(布尔表达式){
	// 语句
}

If the result of the Boolean expression is true, the statement in if is executed, otherwise it is not executed.

For example: Xiao Ming, if you get 90 points or above in this exam, I will reward you with a chicken drumstick.

int score = 92;
if(score >= 90){
    System.out.println("吃个大鸡腿!!!");
}

    2. Grammar format 2

if(布尔表达式){
	// 语句1
}else{
	// 语句2
}

If the result of the Boolean expression is true, the statement in if is executed, otherwise the statement in else is executed.

For example: Xiao Ming, if you get a score of 90 or above in this test, I will reward you with a big chicken drumstick, otherwise I will reward you with a big mouth.

int score = 92;
if(score >= 90){
	System.out.println("吃个大鸡腿!!!");
}else{
	System.out.println("挨大嘴巴子!!!");
}

    3. Grammar format 3

if(布尔表达式1){
	// 语句1
}else if(布尔表达式2){
	// 语句2
}else{
	// 语句3
}

If expression 1 is true, execute statement 1. Otherwise, expression 2 is true, execute statement 2. Otherwise, execute statement 3.

For example: taking into account students' self-esteem, the score ranking will not be disclosed, so:

  • Scores between [90, 100] are considered excellent

  • Scores before [80, 90) are good

  • Scores between [70, 80) are considered moderate

  • Scores between [60, 70) are considered passing

  • Scores between [0, 60) are considered failed

  • Wrong data.

Notify students of their results according to the above method.

public static void main(String[] args) {
    int score = 100;
    if (score >= 90)
        System.out.println("优秀");
    else if (score >= 80 && score < 90)
        System.out.println("良好");
    else if (score >= 70 && score < 80)
        System.out.println("中等");
    else if (score >= 60 && score < 70)
        System.out.println("及格");
    else if (score >= 0 && score < 60)
        System.out.println("不及格");
    else {
        System.out.println("错误数据");
    }
}

Exercise

  1. Determine whether a number is cardinal or even.

public static void main(String[] args) {
    // Scanner:工具   new:创建一个对象   System.in:从键盘输入
    Scanner scanner = new Scanner(System.in);
    
    // scanner.nextInt() -> 接受整型值。
 	int iVal = scanner.nextInt();
    if(iVal % 2 == 0)
        System.out.println("iVal是偶数");
    else
        System.out.println("iVal是奇数");
}
  1. Determine whether a number is positive, negative, or zero.

public static void main(String[] args) {
    // Scanner:工具   new:创建一个对象   System.in:从键盘输入
    Scanner scanner = new Scanner(System.in);
    
    // scanner.nextInt() -> 接受整型值。
    int iVal = scanner.nextInt();
    if(iVal > 0)
        System.out.println("正数");
    else
        System.out.println("负数");
}
  1. Determine whether a year is a leap year.

public static void main(String[] args) {
    // Scanner:工具   new:创建一个对象   System.in:从键盘输入
    Scanner scanner = new Scanner(System.in);
    
    // 判断闰年的公式:
    //(1)四年一闰百年不闰:即如果year能够被4整除,但是不能被100整除,则year是闰年。
    //(2)每四百年再一闰:如果year能够被400整除,则year是闰年。
    // scanner.nextInt() -> 接受整型值。
    int iVal = scanner.nextInt();
    for (int year = 1000; year < iVal; year++)  {
        if ((year % 4 == 0) && (year % 100 != 0))
            System.out.println(year + "->是闰年");
        else if (year % 400 == 0)
            System.out.println(year + "->是闰年");
        else
            System.out.println(year + "->不是闰年");
    }
}

【Precautions】 

  • coding style

// 风格1-----> 推荐
int x = 10;
if (x == 10) {
	// 语句1
} else {
	// 语句2
} 

// 风格2
int x = 10;
if (x == 10)
{
	// 语句1
} else 
{
	// 语句2
}

// 代码风格没有好坏,看个人的爱好。

Although both methods are legal, it is more recommended to use style 1 in Java, { placed on the same line as if / else. The code is more compact.

  • semicolon problem

int x = 20;
if (x == 10);
{
	System.out.println("hehe");
} 
// 运行结果
hehe

An extra semicolon is written here, causing the semicolon to become the statement body of the if statement, and the code in { } has become a code block that has nothing to do with an if.

  • draping else problem

int x = 10;
int y = 10;
if (x == 10)
	if (y == 10)
		System.out.println("aaa");
else
	System.out.println("bbb");

You don't need to add braces in the if / else statement. However, you can also write a statement (only one statement can be written). At this time, else matches the closest if. However, in actual development, we do not recommend writing  this way . It's better to add braces.

【3.2】switch statement

【Basic Grammar】

switch(表达式){
    case 常量值1:{
        语句1;
        [break;]
    }
    case 常量值2:{
        语句2;
        [break;]
    }
    ...
    default:{
        内容都不满足时执行语句;
        [break;]
    }
}

【Implementation process】

  • The expression is evaluated first.

  • Compare with case in sequence, and once there is a matching match, the statements under this item will be executed until break is encountered.

  • When the value of the expression does not match the listed items, default is executed.

[Code Example] Output the day of the week based on the value of day.

public static void main(String[] args) {
    // Scanner:工具   new:创建一个对象   System.in:从键盘输入
    Scanner scanner = new Scanner(System.in);
    
    // scanner.nextInt() -> 接受整型值。
    int iDay = scanner.nextInt();
    switch (iDay){
        case 1:
            System.out.println("星期一");
            break;
        case 2:
            System.out.println("星期二");
            break;
        case 3:
            System.out.println("星期三");
            break;
        case 4:
            System.out.println("星期四");
            break;
        case 5:
            System.out.println("星期五");
            break;
        case 6:
            System.out.println("星期六");
            break;
        case 7:
            System.out.println("星期日");
            break;
        default:
            System.out.println("数值错误");
    }
}

Notes

  • Constant values ​​after multiple cases cannot be repeated.

  • The parentheses of switch can only contain expressions of the following types.

    • Basic types: byte, char, short, int. Note that it cannot be long type.

    • Reference type: String constant string, enumeration type.

double num = 1.0;
switch(num) {
    case 1.0:
        System.out.println("hehe");
        break;
    case 2.0:
        System.out.println("haha");
        break;
}

// 编译出错
Test.java:4: 错误: 不兼容的类型: 从double转换到int可能会有损失
	switch(num) {
	^
1 个错误
  • Don't omit break, otherwise you will lose the effect of "multi-branch selection"

int day = 1;
switch(day) {
    case 1:
        System.out.println("星期一");
        // break;
    case 2:
        System.out.println("星期二");
        break;
}

// 运行结果
星期一
星期二
  • switch cannot express complex conditions

// 例如: 如果 num 的值在 10 到 20 之间, 就打印 hehe
// 这样的代码使用 if 很容易表达, 但是使用 switch 就无法表示.
if (num > 10 && num < 20) {
	System.out.println("hehe");
}
  • Although switch supports nesting, it is very ugly and is generally not recommended~

int x = 1;
int y = 1;
switch(x) {
    case 1:
        switch(y) {
            case 1:
                System.out.println("hehe");
                break;
        }
        break;
    case 2:
        System.out.println("haha");
        break;
}

        The beauty of the code is also an important criterion. After all, this is a world of looks .

        In summary, we found that the use of switch has relatively large limitations.

【4】Loop structure

【4.1】while loop

【Basic Grammar】

while(循环条件){ // 循环条件为 true, 则执行循环语句; 否则结束循环. 
	循环语句;
}

[Code Example 1] Print numbers from 1 to 10.

public static void main(String[] args) {
    int i = 1;
    while(i <= 10){
        System.out.println(i);
        i++;
    }
}

[Code Example 2] Calculate the sum of 1 to 100, the sum of even numbers from 1 to 100, and the sum of odd numbers from 1 to 100 in a loop condition.

public static void main(String[] args) {
    int i = 1;
    int iSum = 0;
    int iEvenSum = 0;
    int iOddSum = 0;
    
    while(i <= 100){
        if (i % 2 == 0) { // 这里是偶数的和
            iEvenSum = iEvenSum + i;
        } else { // 这里是奇数的和
            iOddSum = iOddSum + i;
        }
        // 这里是1-100的和
        iSum = iSum + i;
        i++;
    }
    
    System.out.println("1-100和: " + iSum);
    System.out.println("1-100中偶数和: " + iEvenSum);
    System.out.println("1-100中奇数和: " + iOddSum);
}

[Code Example 3] Calculate the factorial of 5.

public static void main(String[] args) {
    int n = 1;
    int result = 1;
    while (n <= 5) {
        result *= n;
        n++;
    }
    
    System.out.println(result);
}

[Code Example 4] Calculate 1! + 2! + 3! + 4! + 5!

/**
 * 求n的阶层函数
 * @param n 阶层的层数
 * @return 返回n的阶层
 */
public static int StratumSum(int n) {
    // 定义结果值
    int result = 1;
    int i = 1;
    while (i <= n) {
        result *= i;
        i++;
    }
    // 返回n的阶层
    return result;
}

/**
 * 入口函数
 * @param args
 */
public static void main(String[] args) {
    int n = 5;
    int retSum = 0;
    while (n > 0) {
        System.out.println(retSum);
        retSum = retSum + StratumSum(n);
        n--;
    }
    // 打印结果
    System.out.println(retSum);
}


// ----------------------------------------------------------------------------------

/**
 * 入口函数
 * @param args
 */
public static void main(String[] args) {
    int n = 5;
    int retSum = 0;
    while (n > 0) {
        // retSum = retSum + StratumSum(n);
        // 定义结果值
        int result = 1;
        int i = 1;
        while (i <= n) {
            result *= i;
            i++;
        }
        retSum = retSum + result;
        n--;
    }
    System.out.println(retSum);
}

        Here we find that when a code contains multiple loops, the complexity of the code is greatly increased. And more complex codes are more prone to errors. We will use simpler methods to solve this problem later.

【Precautions】

  • Similar to if, the statement below while does not need to write { }, but when it is not written, it can only support one statement. It is recommended to add { }.

  • Similar to if, the { after while is recommended to be written on the same line as while.

  • Similar to if, do not write more semicolons after while, otherwise the loop may not be executed correctly.

int num = 1;
while (num <= 10); {
	System.out.println(num);
	num++;
}

// 执行结果
[无任何输出, 程序死循环]	

        At this time; is the statement body of while (this is an empty statement), and the actual { } part has nothing to do with the loop. At this time, the loop condition num <= 10 is always true, causing the code to loop endlessly.

【4.2】for loop

Basic Grammar

for(表达式①;布尔表达式②;表达式③){
	表达式④;
}
  • Expression 1: Used to initialize the loop variable initial value setting, executed at the beginning of the loop, and only executed once.

  • Expression 2: Loop condition, if full, the loop continues, otherwise the loop ends.

  • Expression 3: Loop variable update method

Execution process

①②③④--->②③④--->②③④--->②③④--->②③④--->②③④--->...--->②为false, the cycle ends.

[Code Example 1] Print numbers from 1 to 10.

public static void main(String[] args) {
    for (int i = 1; i <= 10; i++) {
        System.out.print(i + " ");
    }
}

[Code Example 2] Calculate the sum of 1 to 100, the sum of even numbers from 1 to 100, and the sum of odd numbers from 1 to 100 in a loop condition.

public static void main(String[] args) {
    int iSum = 0;
    int iSumEven = 0;
    int iSumOdd = 0;
    for (int i = 1; i <= 100; i++) {
        if (i % 2 == 0)
            iSumEven = iSumEven + i;
        else
            iSumOdd = iSumOdd + i;
        iSum = iSum + 1;
    }
    
    System.out.println(iSum);
    System.out.println(iSumEven);
    System.out.println(iSumOdd);
}

[Code Example 3] Calculate the factorial of 5.

public static void main(String[] args) {
    int sum = 1;
    for (int i = 1; i <= 5; i++) {
        sum *= i;
    }
    
    System.out.println(sum);
}

[Code Example 4] Calculate 1! + 2! + 3! + 4! + 5!

/**
 * 求n的阶层函数
 * @param n 阶层的层数
 * @return 返回n的阶层
 */
public static int StratumSum(int n) {
    int ret = 1;
    for (int j = 1; j <= n; j++) {
        ret *= j;
    }
    return ret;
}
public static void main(String[] args) {
    int sum = 0;
    for(int i = 1; i <= 5; i++) {
        int ret = StratumSum(i);
        sum = sum + ret;
    }
    
    System.out.println(sum);
}


// ----------------------------------------------------------------------------------


/**
 * 入口函数
 * @param args
 */
public static void main(String[] args) {
    int sum = 0;
    for(int i = 1; i <= 5; i++) {
        int ret = 1;
        for (int j = 1; j <= i; j++) {
            ret *= j;
        }
        sum = sum + ret;
    }
    
    System.out.println(sum);
}

[Notes] (Similar to while loop)

  • Similar ifto , forthe following statement does not need to be written { }, but only one statement can be supported when it is not written. It is recommended to add it { }.

  • Similar to if, forthe following { suggestions and whileare written on the same line.

  • Similar to if, fordo not write more semicolons after it, otherwise the loop may not be executed correctly.

  • Like the while loop, it is used to end a single loop continueand to end the entire loop break.

【4.3】do while loop

【Basic Grammar】

do{
	循环语句;
}while(循环条件);

The loop statement is executed first, and then the loop condition is determined. If the loop condition is established, execution continues, otherwise the loop ends.

For example: print 1 - 10

int num = 1;
do {
	System.out.println(num);
	num++;
} while (num <= 10);

【Precautions】

  • do whileDon’t forget the semicolon at the end of the loop.

  • Generally, do whileit is rarely used, and it is more recommended to use for and while.

【4.4】break keyword

    breakThe function is to end the loop early.

Code example: Find the first multiple of 3 in 100 - 200.

public static void main(String[] args) {   // 针对其他的循环语句是一样的用法
    int begin = 100;
    while(begin <= 200){
        if(begin % 3  == 0) {
            break;
        }
        begin++;
    }
    System.out.println(begin);
}

// 执行结果:找到了 3 的倍数, 为:102

breakThe loop will end when it is executed .

【4.5】continue keyword

continueThe function is to skip this cycle and immediately enter the next cycle.

Code example: Find the first multiple of 3 in 100 - 200.

public static void main(String[] args) {	// 针对其他的循环语句是一样的用法
    int begin = 100;
    while(begin <= 200){
        if(begin % 3  == 0) {
            continue;
        }
        begin++;
    }
    System.out.println(begin);
}

// 死循环begin++永远都不可能被执行。

        When the statement is executed continue, it will immediately enter the next loop (to determine the loop condition), so that the print statement below will not be executed.

【5】Input and output

【5.1】Output to console

System.out.println(msg); // 输出一个字符串, 带换行
System.out.print(msg); // 输出一个字符串, 不带换行
System.out.printf(format, msg); // 格式化输出
  • printlnThe output content comes with it \nor printnot \n.

  • printfprintfThe formatted output method is basically the same as that of C language .

【Code example】

public static void main(String[] args) {
    String msg = "傻响";
    System.out.println(msg);
    System.out.print(msg + "\n");
    System.out.printf("%s\n", msg);   
}

[Format string]

conversion character type Example
d decimal integer ("%d", 100) 100
x hexadecimal integer ("%x", 100) 64
o Octal integer ("%o", 100) 144
f Fixed point floating point number ("%f", 100f) 100.000000
e Exponential floating point number ("%e", 100f) 1.000000e+02
g general floating point numbers ("%g", 100f) 100.000
a Hexadecimal floating point number ("%a", 100) 0x1.9p6
s string ("%s", 100) 100
c character ("%c", ‘1’) 1
b Boolean value ("%b", 100) true
h Hash code ("%h", 100) 64
% percent sign ("%.2f%%", 2/7f) 0.29%

There is no need to memorize this form, just look it up when needed.

【5.2】Input from keyboard

[Example code] Use Scanner to read strings/integers/floating point numbers.

import java.util.Scanner; // 需要导入 util 包


// 问题一:
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    
    System.out.print("请输入姓名:> ");
    
    // No.1 如果是next那么读取是会碰到空格就结束.
    String name = scanner.next();
    // 打印结果:
    请输入姓名:> Sha Xiang
	姓名: Sha
    
    // No.2 nextLine会读取一行.
    String name = scanner.nextLine();
    // 打印结果:
    请输入姓名:> Sha Xiang
	姓名: Sha Xiang
    
    System.out.println("姓名: " + name + "," + "年龄: ");
    scanner.close();
}

// 问题二:
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    // 先读取年龄(整型)
    System.out.print("请输入年龄:> ");
    int age = scanner.nextInt();
    
    // 如果先读取的是整数、浮点数,没有先读取字符串,就需要这样处理掉隐藏的'\n',否则下面的			就会失效。
	scanner.nextLine(); 
	// 最后读取名字(字符串)
    System.out.print("请输入姓名:> ");
    String name = scanner.nextLine();


    System.out.println("姓名: " + name + "," + "年龄: " + age);
    scanner.close();
}

// ----------------------------------------------------------------------------------

// 正常的代码:
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    
    // 这样的顺序是没问题的-》先处理字符串√
    System.out.print("请输入姓名:> ");
    String name = scanner.nextLine();
    
    System.out.print("请输入年龄:> ");
    int age = scanner.nextInt();
    
    System.out.print("请输入工资:> ");
    double salary = scanner.nextDouble();
    
    System.out.println("姓名: " + name + "," + "年龄: " + age + "," + "工资: " + salary + "元");
    scanner.close();
}
// 打印结果:
// 请输入姓名:> 傻响
// 请输入年龄:> 18
// 请输入工资:> 
// 22.12
// 姓名: 傻响,年龄: 18,工资: 22.12

[Example code] Use Scanner to read N numbers in a loop and calculate their average value.

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int sum = 0;
    int cnt = 0;
    
    // scan.hasNextInt()
    // 如果此扫描仪输入中的下一个标记可以使用nextInt()方法解释为指定基数中的int值,则返回true。 扫描仪不会超过任何输入。 
    // 当且仅当此扫描器的下一个令牌是有效的int值时才为真 
    while(scan.hasNextInt()) {  // Ctrl + d程序会自己结束掉.
        sum += scan.nextInt();
        cnt++;
    }
    
    System.out.println("总和: " + sum);
    System.out.println("平均值: " + sum / cnt);
    scan.close();
}

Note:  When inputting multiple data in a loop, use ctrl + z to end the input (ctrl + z on Windows, ctrl + d on Linux/Mac). In subsequent oj questions, you will encounter IO type algorithm questions. , there are various requirements for loop input, which will be introduced later.

【6】Guess the number game

【game rules】

        The system automatically generates a random integer (1-100), and then the user enters a guessed number. If the entered number is smaller than the random number, it prompts "low"; if the entered number is larger than the random number, it prompts "high" "", if the entered number is equal to the random number, it will prompt "guessed correctly".

【Reference Code】

public static void main(String[] args) {
    // new随机数对象
    Random random = new Random();
    // 给出随机数
    int randomNumber = random.nextInt(100) + 1; // 【0 - 99】 + 1 = 【0 - 100】
    Scanner scan = new Scanner(System.in);
    
    // 进入死循环开始猜数字
    int cnt = 1;
    while(true) {
        System.out.println("第" + cnt + "次>请输入猜测的数字:> ");
        cnt++;
        
        int input = scan.nextInt();
        if(input > randomNumber){
            System.out.println("猜大了");
            continue;
        } else if (input < randomNumber) {
            System.out.println("猜小了");
            continue;
        } else {
            System.out.println("猜中了");
            break;
        }
    }
    scan.close();
}

Guess you like

Origin blog.csdn.net/lx473774000/article/details/131496286