current position:Home>Java process control

Java process control

2022-02-04 17:13:06 Little Zhang Ya

Scanner object

Java It provides us with a tool class that can obtain user input .java.util.Scanner yes Java5 New features , We can go through Scanner Class to get user input .

Basic grammar :Scanner s = new Scanner(System.in);

adopt Scanner Class next() And nextLine() Method to get the input string , We usually need to use hasNext() And hasNextLine() Determine whether there is any input data .

next():

  1. You must read valid characters before you can end the input .
  2. Whitespace encountered before entering valid characters for ,next() Method will automatically remove it .
  3. The space entered after a valid character is used as a separator or terminator only after it is entered .
  4. next() Cannot get string with space .

nestLine():

  1. With Enter End of character , in other words nextLine() Method returns all the characters before enter .
  2. Can get blank .

Be sure to turn off resources

Sequential structure

JAVA The basic structure of the system is the order structure , Exclude specified , Otherwise, it is executed sentence by sentence in order .

Sequence structure is the simplest algorithm structure .
 Sequential structure

Between statements , Box to box is done from top to bottom , It consists of several processing steps that are executed in turn , It is a basic algorithm structure that any algorithm can't do without .

Selection structure

  • if Single choice structure
if( Boolean expression ){
  // If the Boolean expression is true Statement to be executed 
}

if Single choice structure

  • if Double choice structure
if( Boolean expression ){
  // If the value of a Boolean expression is true
} else {
  // If the value of a Boolean expression is false
}

if Double choice structure

  • if Multiple choice structure
if( Boolean expression 1){
    // If the Boolean expression 1 The value of is true Execute code 
} else if( Boolean expression 2){
    // If the Boolean expression 2 The value of is true Execute code 
} else if( Boolean expression 3){
    // If the Boolean expression 3 The value of is true Execute code 
} else {
    // If none of the above Boolean expressions are true Execute code 
}

if Multiple choice structure

  • Nested if structure
if( Boolean expression  1){
    // If the Boolean expression  1  The value of is true Execute code 
    if( Boolean expression  2){
        // If the Boolean expression  2  The value of is true Execute code 
    }
}
  • switch Multiple choice structure
//switch  Match a specific value 
switch(expression){
    case value :
        // sentence 
        break:// Optional , The main function is to prevent case through 
    case value:
        // sentence 
        break:
    // You can have any number of case sentence 
    default:// Optional , When there is no match case when , It can be used default expression 
        // sentence 
}

switchi The variable type in a statement can be :byte、short、int perhaps char.
from Java SE 7 Start :switch Support string String type .
meanwhile case Label must be a string constant or literal

Loop structure

  • while loop
while( Boolean expression ){
   // Cycle content 
}

1、 Only Boolean expressions are true, The cycle will continue .
2、 Most of the time we stop the cycle , We need a way to fail the expression to end the loop .
3、 A small number of cases require a loop to be executed all the time , For example, the server's request response monitoring and so on .
4、 The cycle condition is always true It creates an infinite loop 【 Dead cycle 】, We should try our best to avoid dead loops in normal business programming , It will affect the performance of the program or cause the program to jam and crash !

  • do…while loop

1、 about while Statement , If you don't do that , You can't go into a cycle . But sometimes we need even if we don't meet the conditions , also At least once .
2、do … while Circulation and while Cyclic similarity , The difference is ,do … while The loop will execute at least once .

do{
  // Code statements 
} while( Boolean expression )

while and do-while The difference between :
while Judge before you execute .do-while It's execution before judgment !
Do … while Always make sure that the loop is executed at least once ! That's the main difference between them .

  • for loop

for Circular statement is a general structure that supports generation , Is the most effective , The most flexible loop structure .

for ( initialization ; Boolean expression ; to update ){
   // Code statements 
}

1、 Perform the initialization step first , You can declare a type , However, one or more loop control variables can be initialized , It can be an empty sentence .
2、 then , Check the value of a Boolean expression , If it is true, The circulatory body is executed ; If false, Cycle termination , Start executing the statement after the loop body .
3、 After performing a cycle , Update loop control variables ( The iteration factor controls the increase or decrease of cyclic variables ).
4、 Check the Boolean expression again , Loop through the above process .

Print the multiplication table

public static void main(String[] args) {
        System.out.println(" multiplication table :");
        for (int j = 1; j < 10; j++) {
            for (int i = 1; i <= j; i++) {
                System.out.print(i + "*" + j + "=" + (i * j)+" ");
            }
            System.out.println();
        }
    }
  • Enhanced for loop .

Java5 The introduction of a method mainly used for Array or collection Enhanced for loop .

for( Statement statement : expression )
{
    // Code sentence 
}

Statement statement : Declare new local variables , The type of the variable must match the type of the array element . Its scope is limited to the loop statement block , Its value is equal to the value of the array element at this time .
expression : Expression is the name of the array to be accessed , Or the return value is an array .

break continue

  • break In the body of any loop statement , All available break Control the flow of the cycle .break Used to force out of the loop , Do not execute the remaining statements in the loop .(break Sentences are also switchi Use in statement ).

  • continue Statement is used in the body of a loop statement , Used to terminate a cycle process , That is to skip the statement that has not been executed in the loop body , Then, determine whether to execute the cycle next time .

About goto keyword :
goto Keywords have long been used in programming languages , Even though goto Is still Java A reserved word of , But it's not officially used in language ; Java No, goto . However , stay break and continue These two keywords , We can still see some goto Shadow --- Tagged break and continue.
“ label ” An identifier followed by a colon , for example : label:
Yes Java For example, the only place to use a tag is before the loop statement . And the only reason to set the label before the loop is : We want to nest another loop in it , because break and continue Keywords usually break only the current loop , But if used with a label , They'll break to where the tag is
.

outer: for (int i = 101; i < 150; i++){
        for (int j = 2; j < i/2; j++){
           if (i % j == 0){
               continue outer;// When the conditions are met, return to  outer  Record location and rerun .
          }
        }
        System.out.println(i);
    }

practice : Print triangles

for (int i = 1; i <= 5; i++) {
    for (int j = 5; j >=i; j--) {
        System.out.print(" ");
    }
    for (int j = 1; j <=i; j++){
        System.out.print("*");
    }
    for (int j = 1; j < i; j++){
        System.out.print("*");
    }
    System.out.println();
}

copyright notice
author[Little Zhang Ya],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/02/202202041713035514.html

Random recommended