Collect it now! You don't know the process control knowledge in Java. Why do you raise your salary?

The
basic stage catalog of Java process control :
user interaction Scanner
sequence structure
selection structure
loop structure
break & continue
exercises
1. Scanner object
The basic grammar we learned before did not realize the interaction between programs and people, but Java provides us with such a Tools, we can get user input. Java.util.Scanner is a new feature of Java5, we can get user input through the Scanner class.

Basic syntax:

Scanner s = new Scanner(System.in);

Get the input string through the next() and nextLine() methods of the Scanner class. Before reading, we generally need to use hasNext() and hasNextLine() to determine whether there is still input data.

next():

You must read valid characters before you can end the input. //It must be entered otherwise the program will not stop

For the blanks encountered before entering valid characters, the next() method will automatically remove them. //Hello World only outputs Hello because of spaces

Only when a valid character is entered, the blank entered after it will be used as a separator or terminator. /'/End only if there is a space in the program'

next() cannot get a string with spaces.

Examples of using next():

package com.company.base;

import java.util.Scanner;

public class demo1 {

public static void main(String[] args) {

    //创建一个扫描器对象,用于接受键盘数据
    Scanner scanner = new Scanner(System.in);

    System.out.println("使用next方式接收:");

    //判断用户有没有输入字符串
    if (scanner.hasNext()){
        //使用next方式接收
        String str = scanner.next();
        System.out.println("输出的内容为:"+str);
    }
    scanner.close(); //IO流的用完记得关掉 占用内存 IO流就是输入输出流 和电脑交换信息的
}

}

NextLine()
takes Enter as the terminator, which means that the nextLine() method returns all the characters before the carriage return.
Can get blanks.
package com.company.base;

import java.util.Scanner;

public class demo2 {

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    System.out.println("请输入数据");

    if(scanner.hasNextLine()){
        String abc = scanner.nextLine();
        System.out.println("输出:"+abc);
    }
    scanner.close();
}

}

Scanner
package com.company.base for judging integers and decimals ;

import java.util.Scanner;

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

    //从键盘接收数据
    int i = 0;
    float f = 0.0f;

    System.out.println("请输入整数:");

    //如果。。。那么。。。
    if (scanner.hasNextInt()){
        i = scanner.nextInt();
        System.out.println("整数数据:"+ i);
    }else {
        System.out.println("输入的不是整数数据");
    }
    System.out.println("请输入小数");
if (scanner.hasNextFloat()){
    f = scanner.nextFloat();
    System.out.println("小数数据:"+ f);
}else {
    System.out.println("输入的不是小数数据!");
}

scanner.close();

}

}

Make a simple calculator

package com.company.base;

import java.util.Scanner;

public class demo5 {

public static void main(String[] args) {
    //我们可以输入多个数字,并求其总和与平均数,每一个数字用回车确认,通过输入非数字来结束输入并输出执行结果:
    Scanner scanner = new Scanner(System.in);

    //和
    double sum = 0;
    //计算输入了多少个数字
    int m = 0;

    //通过循环判断是否还有输入,并在里面对每一次进行求和和统计
    while (scanner.hasNextDouble()){

        double x = scanner.nextDouble();

        m = m+1;//m++

        sum = sum + x;

        System.out.println("你输入了第"+m+"个数据,然后点钱结果sum"+sum);
    }

    System.out.println(m +"个数的和为"+ sum);
    System.out.println(m+ "个数的平均值是"+(sum / m));

    scanner.close();
}

}

2. Sequence structure
The basic structure of Java is the sequence structure, unless otherwise specified, the responsibility is executed in accordance with the order.

The sequence structure is the simplest algorithm structure.

Between sentences and sentences, boxes and boxes are carried out in the order from top to bottom. It is composed of several processing steps executed in sequence. It is a basic algorithm that cannot be separated from any algorithm. structure.

If you haven’t figured it out yet, just give the RUN below and you’ll know

package com.company.base;

public class demo6 {
public static void main(String[] args) {
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
System.out.println("5");
System.out.println("6");
System.out.println("7");
System.out.println("8");
}
}

3. Select structure (very important)
if single-select structure
if double-select structure
if multiple-select structure
nested if structure
switch multiple-select structure
if single-select structure
We often need to judge whether something is feasible, and then we execute , Such a process is represented by an if statement in the program

grammar:

if(Boolean expression){
//The statement that will be executed if the Boolean expression is true, otherwise skip
}

When the if double-choice structure
requires two judgments, a double-choice structure is needed, so there is an if-else structure.
Syntax:
if(Boolean expression){
//If the value of the Boolean expression is true
}else{
//If the value of the Boolean expression is false
}

package com.company.ifdemo;

import java.util.Scanner;

public class if2 {

public static void main(String[] args) {
//考试分数大于60就是及格,小于60分就是不及格
    Scanner scanner = new Scanner(System.in);

    System.out.println("请输入成绩:");

    int score = scanner.nextInt();

    if (score>60){
        System.out.println("及格");
    }else {
        System.out.println("不及格");
    }
}

}

If multi-select structure,
we found that the code just now does not meet the actual situation. In the real situation, there may be ABCD, and there are interval multi-level judgments. For example, 90-100 is A, 80-90 is B, and so on. In many cases in life, our choices are more than just these two, so we need a multi-choice structure to deal with such problems.
if(Boolean expression 1){
//Execute code
if the value of Boolean expression 1 is true }else if(Boolean expression 2){
//Execute code
if the value of Boolean expression 2 is true }else if(Boolean expression Equation 3){
//Execute code if the value of Boolean expression 3 is true
}else{
// Execute code if none of the above Boolean expressions are true
}

package com.company.ifdemo;

import java.util.Scanner;

public class if3 {

public static void main(String[] args) {
    //考试分数大于60就是及格,小于60分就是不及格
    Scanner scanner = new Scanner(System.in);

    System.out.println("请输入成绩:");

    int score = scanner.nextInt();

/ The
if statement has at most one else statement, and the else statement follows all else if statements.
The if statement can have several else if statements, and they must precede the else statement.
Once one of the else if statements is detected as true, the other else if and else statements will be skipped execution
/
if (score == 100) {
System.out.println("Congratulations, you got full marks");
} else if (score <100 && score >= 90) {
System.out.println("A-level");
} else if (score <90 && score >=80) {
System.out.println("B-level");
} else if (score <80 && score >= 70) {
System.out.println("C-level");
}else if (score<70 && score>=60){
System.out.println("D-level") ;
}else if (score<60 && score>=0){
System.out.println("Failed to pass and study hard");
}
}
}

  1. Nested if structure

    • It is legal to use nested if...else statements. In other words, you can use an if or else if statement in another if or else if statement. You can nest else if...else like if statements.

    • Syntax
      if (Boolean expression 1) {
      //Execute code
      if the value of Boolean expression 1 is true if (Boolean expression 2) {
      // Execute code if the value of Boolean expression 2 is true
      }
      }

4. Switch multi
-choice structure There is another way to realize the multi-choice structure is the switch case statement.
The switch case statement can determine whether a variable is equal to a certain value in a series of values, and each value is called a branch.
The variable type in the switch statement can be:
byte, short, int, or char.
Starting from Java SE 7,
switch supports the string String type,
and the case label must be a string constant or a literal.
Switch(expression){
case value:
//statement
break;//optional
case value:
//statement
break;//optional
//you can have any number of case statements
default://optional
//statement
}

The first example:

package com.company.jiaohuan;

public class JH {
public static void main(String[] args) {
//
char grade = 'A';

    switch (grade){
        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("未知等级");
    }
}

}

The second example:

package com.company.jiaohuan;

public class JH2 {
public static void main(String[] args) {
String name = "chb";
//New feature of JDK 7, the expression result can be a string! ! !
//The nature of characters is still numbers! ! !

    //反编译 java----class(字节码文件)---反编译(IDEA)

switch (name){
case "RAP":
System.out.println("RAP");
break;
case "整活":
System.out.println("整活");
default:
System.out.println("妹有啊");
}
}
}

5. Loop structure
while loop
while (Boolean expression) {
// loop content
}

  • As long as the Boolean expression is true, the loop will continue to execute.
  • In most cases, we will stop the loop. We need a way to invalidate the expression to end the loop.
  • A small number of cases need to be executed in a loop, such as server request response monitoring.
  • If the loop condition is always true, it will cause an infinite loop [infinite loop] In our normal business programming, we should try to avoid infinite loop. It will affect the performance of the program or cause the program to
    freeze and crash! package com.company.whiledemo01;

public class Whiledemo1 {
public static void main(String[] args) {

    //输出1-100

    int i = 0;

    while (i < 5201314){

        i++;
        System.out.println(i);
    }
}

}

Calculate 1+2+. . +100

public class Whiledemo3{
public static void main(String[] args) {
//计算1+2+。。+100

    int i = 0;
    int sum = 0;
    while (i<=100){
        sum = sum + i;
        i++;
    }
    System.out.println(sum);
}

}

do...while loop

For the while statement, if the condition is not met, it cannot enter the loop. But sometimes we need to execute at least once even if the conditions are not met.

The do...while loop is similar to the while loop, the difference is that the do...while loop will be executed at least once

do{
//Code statement
}while(Boolean expression);

Use the do...while statement to calculate 1+2+. . +100
package com.company.whiledemo01;

public class dowhiledemo1 {
public static void main(String[] args) {
int i = 0 ;
int sum = 0 ;
do{
sum = sum + i;
i++;
}while ((i<=100));
System.out.println(sum);
}
}

public class dowhiledemo2{
public static void main(String[] args) {

    int a = 0;
    while (a<0){
        System.out.println(a);
        a++;
    }
    System.out.println("===========");
    do{
        System.out.println(a);
        a++;
    }while (a<0);
}

The difference between while and do...while:

While judged first and then executed, dowhile is executed first and then judge!

DO...while always guarantees that the loop body will be executed at least once! This is their main difference.

for loop

An enhanced for loop mainly used for arrays is introduced in Java5

Guess you like

Origin blog.51cto.com/14966465/2543072