【Java】Process Control

sequential structure

The most basic structure of the program. If there are no special circumstances, it will be executed sentence by sentence. There is not much to introduce about this.

Select structure

ifstatement

//格式1
if(布尔表达式){
    
    
	//表达式为true就执行
}

//格式2
if(布尔表达式){
    
    
	//表达式为true就执行
}else{
    
    
    //表达式为false就执行
}

//格式3
if(布尔表达式1){
    
    
    
}else if(布尔表达式2){
    
    
    
}else if(布尔表达式N){
    
    
    
}else{
    
    
    //上面可以有无限个分支,满足哪个就执行哪个
    //都不满足才会走else语句
}

Please write a statement with the structure if as follows

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 failing

Anything outside the range is error data

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int score = 90;
        if (score >= 90 && score <= 100) {
    
    
            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("错误数据");
        }
    }
}

practise

Determine whether a year is a leap year

Leap year: The year is divisible by 4 and not divisible by 100, or it is divisible by 400

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int year = 2012;
        //加好括号保证运算正常运行
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
    
    
            System.out.println("是闰年");
        } else {
    
    
            System.out.println("不是闰年");
        }
    }
}

Here I will mention the code format, taking the above code as an example.

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int year=2012;
        if((year%4==0&&year%100!=0)||(year%400==0)){
    
    
            System.out.println("是闰年");
        }else{
    
    
            System.out.println("不是闰年");
        }
    }
}

As you can see, the above code is crowded into a lump and is very ugly. Even if it is not beautiful, the readability of the code is very low.

Although IDEA supports shortcut key formattingCtrl+Alt+L, it is still recommended to develop good writing habits. You can also use this shortcut key to see the formatted code and yourself. What is the difference between the codes? Learn the standard writing method

switchstatement

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

When the value of the expression is equal to the constant N, execute the statement of that branch. If none of them match, execute the statement of default

There are some points to note about this statement:

  1. Constant value expression cannot be of typeboolean long float double
  2. breakNo leakage, otherwise it will happencasePenetration
public class Test {
    
    
    public static void main(String[] args) {
    
    
        int day = 1;
        switch (day) {
    
    
            case 1:
                System.out.println("星期一");
                // break;
            case 2:
                System.out.println("星期二");
                break;
        }
        //这里执行的结果就是 
        //星期一 
        //星期二
    }
}

Loop structure

whilecycle

while(布尔表达式){
    
    
    //表达式为true就进入循环
	循环语句;
}

When using a loop structure, we generally need to adjust the quantities involved in the Boolean expression in the loop statement to control the number of loop executions.

Write a code below that calculates the sum of 0-100

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int i = 0;
        int sum = 0;
        while (i <= 100) {
    
    
            sum += i;
            //对表达式涉及的量进行调整从而控制循环次数
            i++;
        }
        System.out.println(sum);
    }
}

breakandcontinue

break is used to jump out of the loop, continue is used to skip the statement after continue in the loop

Give two examples to illustrate

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int a = 0;
        while (a < 10) {
    
    
            a++;
            System.out.println(a);
            if (a == 5) {
    
    
                break;
            }
            //a为5的时候跳出循环,相当于直接硬性结束循环
            //结果为1 2 3 4 5
        }
    }
}
public class Test {
    
    
    public static void main(String[] args) {
    
    
        int a = 0;
        while (a < 10) {
    
    
            a++;
            if (a == 5) {
    
    
                continue;
            }
            //a为5的时候跳过后面的语句,直接进入下一次循环
            System.out.println(a);
            //结果为1 2 3 4 6 7 8 9 10
        }
    }
}

forcycle

There is no essential difference between the for loop and the while loop, but they are easier to write. Writing two equivalent loops helps to understand

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

        int a = 1;
        while (a <= 100) {
    
    
            System.out.print(a+" ");
            a = a + 1;
        }
    }
}

But there are a few points to note

  1. The code adjustment part is not exactly located at the bottom of the curly braces like while, but is in an independent area and is executed after the code in the curly braces has finished running.
public class Test {
    
    
    public static void main(String[] args) {
    
    
        for (int a = 1; a <= 10; a++) {
    
    
            if (5 == a) {
    
    
                continue;
            }
            System.out.print(a + " ");
            //这样只会跳过5,而不会死循环
        }
        
        
        //下面这个则是死循环写法
        int b = 1;
        while (b <= 10) {
    
    
            if (5 == b) {
    
    
                continue;
            }
            System.out.print(b + " ");
            b++;
        }
    }
}

The operation of the for loop is more like the following figure

Insert image description here

  1. Try not to modify loop variables inside the for loop, as this may cause the for loop to get out of control.
  2. It is recommended that the value of the loop control variable of the for statement be written in the front-closed-then-open interval format
public class Test {
    
    
    public static void main(String[] args) {
    
    
        //前闭区间 指int a = 0; 后开区间 指a < 10;
        for (int a = 0; a < 10; a++) {
    
    
            System.out.println(a + " ");
        }
        
        System.out.println();
        
        for (int a = 0; a <= 9; a++) {
    
    
            System.out.println(a + " ");
        }
         //上下两个循环输出结果完全相同
		//但是上面为前闭后开区间写法,下面为前闭后闭区间写法
		//当我们使用前闭后开区间写法时,可以直观的看出循环了10次,而下面的写法不能
    }
}

do whilecycle

A statement that is executed once first and then is judged as to whether it is looping, that is to say, it can be run at least once no matter whether the conditions are met or not.

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int a = 0;
        do {
    
    
            System.out.println(a + " ");
        } while (a >= 1);
        //while后面有个分号别忘了
        //会输出个 0
    }
}

input and output

After learning the selection structure and loop structure, we often encounter some problems that need to receive data and output data, so here is a brief introduction to how input and output in Java operate.

output

basic grammar

System.out.println(msg);
System.out.print(msg);
System.out.printf(format, msg);

We have already used the first two. The difference between the first and the second is that the first one comes with it\n (that is, line break)

Regarding the formatted output ofprintf, here is an example to help understand

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int a = 0;
        System.out.printf("a = %d",a);
        //相当于定好一个格式,然后中间插入一些指示符,指示符依次对应着后面的变量
    }
}

Some common indicators are as follows

type of data indicator
int %d
double %lf
float %f
string %s
character %c
long %ld

In fact, if you have learned C language, just treat it asprintf

However, this printing format is not commonly used in Java, so just understand it.

enter

In Java, if we want to read keyboard input data, we need to use a class calledScanner

But we will learn more about it in the classes and objects chapter. Here we just need to remember how to call this class.

import java.util.Scanner;
//首先是导包,因为是调用事先定义好的代码所以要导入
public class Test {
    
    
    public static void main(String[] args) {
    
    
        //然后是创建一个Scanner类,下面例子中sc是名字,随便起,其他的都是固定的
        Scanner sc = new Scanner(System.in);
        
        //中间就可以使用这个类了
             
        //使用完要关闭,格式固定
        sc.close();
    }
}

So how do we use this class to receive keyboard input information? Continuing the above example, we have the following format to receive data

sc.next();//接收数据直到遇到空格或回车为止,通常用于接收单个字符
sc.nextLine();//接收下一行整行的数据,通常用于接收字符串
sc.nextInt();//接收int整型
sc.nextFloat();//接收float类型数据
//其他的各个类型都是差不多的不写了

In additionScanner also provides statements to determine whether there is input

sc.hasNext();//判断是否有输入,有就返回true
//其他的都是类型格式就不写了

This is still very useful in some questions involving multiple sets of data input.


Scanner usage and precautions

Write a code that receives three data: name, age, and phone number, and outputs them

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入姓名");
        String name = sc.nextLine();
        System.out.println("请输入年龄");
        int age = sc.nextInt();
        System.out.println("请输入电话号码");
        String tele = sc.nextLine();
        System.out.println("姓名:" + name + " 年龄:" + age + " 电话:" + tele);
        sc.close();
    }
}

The above code seems to have no problem, but if we enterzhangsan 18 and press Enter, we will find that the code ends directly

So why?

In fact, we might as well recall that when we entered the data above, did we enter it in the following format?

zhangsan \n
18 \n

So how is reading done?

First, read a whole line of data until it reads \n and end directly (the line break will be taken away but not saved). Then the first line is taken away at this time, leaving the second line of 18\n, so since nextInt() will only read intThen take away18 and leave\n. So the next time we read, nextLine() will end directly after reading this \n and will not let us enter data

So how do we solve this problem?

Every time we call the method of reading the type, if we want to read data later, we will add an empty read after the reading of the reading type and take away the newline.

The modified code is as follows

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入姓名");
        String name = sc.nextLine();
        System.out.println("请输入年龄");
        int age = sc.nextInt();
        //加一个空读取
        sc.nextLine();
        System.out.println("请输入电话号码");
        String tele = sc.nextLine();
        System.out.println("姓名:" + name + " 年龄:" + age + " 电话:" + tele);
        sc.close();
    }
}

Then the above code can run normally


Use Scanner to loop to readN numbers and calculate their average value

This mainly involvesScanner the use of judging input methods, but in fact there is no big change, just go to the code

import java.util.Scanner;
public class Test {
    
    
    public static void main(String[] args) {
    
    
        //创建计数器和总和
        int count = 0;
        int sum = 0;
        //创建Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入第一个数字");
        //循环接收
        while(sc.hasNextInt()){
    
    
            sum += sc.nextInt();
            count++;
            System.out.println("请输入第"+(count+1)+"个数字");
        }
        //打印
        System.out.println((double)sum/count);
        //关闭Scanner
        sc.close();
    }
}

When we compile ourselves, we can stop input by pressing Ctrl+D

Some places say that Windows presses Ctrl+Z and Linux presses Ctrl+D, but when I tested IDEA here, I could only Ctrl+D. The reason is unknown
(Anyway, if one doesn’t work, just try the other one)

practise

Guess the number game

Requirement: Randomly generate numbers from 0 to 100, and determine after each input whether the entered number is greater than, less than, or equal to the random number.

Output if it is greater than 猜大了, and let the player re-enter. If it is less than 猜小了, output it and let the player re-enter. Output if equal恭喜你,猜对了

Random number generation

A class in Java is also used here, Random class, which is somewhat similar in usage to Scanner

import java.util.Random;
//导入包 你new Random的时候点击Tab键会自动导入
public class Test {
    
    
    public static void main(String[] args) {
    
    
        //新建一个Random,固定格式暂时不用理解
        Random r = new Random();
    }
}

Then we can use the new one we just createdr to randomize a number

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Random r = new Random();
        int num = r.nextInt(101);
        //这个代码的意思是 随机生成一个大于等于0,小于101的数字 [0,101)
    }
}

The starting point can only be0, so if we want to generate a random number of 50~100, we can use the addition operation

    Random r = new Random();
    int num = r.nextInt(51) + 50;

After generating the numbers, the next step is to receive the numbers entered by the player and make a judgment.

Since we don’t know how many times the player will guess, we use an infinite loop. Then create three branches respectively, corresponding to the three situations. In the case of equal to, output the victory statement, and use break to jump out of the loop directly

        while(true){
    
    
            System.out.println("请输入猜测数");
            int guess = sc.nextInt();
            if (guess == num) {
    
    
                System.out.println("恭喜你猜对了");
                System.out.println("游戏结束");
                break;
            } else if (guess < num) {
    
    
                System.out.println("猜小了");
            } else {
    
    
                System.out.println("猜大了");
            }
        }

Code overview

import java.util.Random;
import java.util.Scanner;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        Random r = new Random();
        int num = r.nextInt(101);
        while(true){
    
    
            System.out.println("请输入猜测数");
            int guess = sc.nextInt();
            if (guess == num) {
    
    
                System.out.println("恭喜你猜对了");
                System.out.println("游戏结束");
                break;
            } else if (guess < num) {
    
    
                System.out.println("猜小了");
            } else {
    
    
                System.out.println("猜大了");
            }
        }
        sc.close();
    }
}

Guess you like

Origin blog.csdn.net/qq_42150700/article/details/130177842