3, Java process control

User interaction Scanner Scanner object

Basic syntax for creating Scanner objects:
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 judge whether there is any input data.

next & nextLine

  1. The next() method receives data
public static void main(String[] args) {    
//Create a scanner object to receive keyboard data
   Scanner scanner = new Scanner(System.in);    
   //Receive string in next mode
   System.out.println("Next Mode reception:");    
   //Judge whether the user has entered any characters
   if (scanner.hasNext()){
       String str = scanner.next();
       System.out.println("Input content:"+str);  
       }
   //All classes belonging to IO stream will always occupy resources if they are not closed Get into the habit of turning it off when you run out It's like you have to turn off the tap after you get the water If you don't shut down a lot of download software or video software completely, you will upload and download it by yourself, which will occupy resources. You will feel that it's a card
   scanner.close(); 
}

  1. The nextLine() method receives data
public static void main(String[] args) {    
   Scanner scan = new Scanner(System.in);    
	// Receive data from keyboard
	
   // Receive string in nextLine mode
   System.out.println("nextLine Reception mode:");    
   // Determine whether there is any input
   if (scan.hasNextLine()) {
       String str2 = scan.nextLine();
       System.out.println("Input content:" + str2);  
       }
   scan.close(); 
}
  1. The difference between the two

next():
1. Be sure to read valid characters before you can end the input.
2. The next() method will automatically remove the blank space encountered before entering valid characters.
three. Only after entering a valid character, the blank space entered after it will be used as a separator or Terminator ('' the string after the space cannot be received).
4. next() cannot get a string with spaces.

nextLine(): (common)
1. Take Enter as the ending character, that is, the nextLine() method returns all characters before entering carriage return.
2. You can get blank.

Scanner advanced use

If you want to input data of type int or "oat", it is also supported in the Scanner class, but you'd better use hasNextXxx() method to verify before entering, and then use nextXxx() to read:

public static void main(String[] args) {    
   Scanner scan = new Scanner(System.in);    
// Receive data from keyboard
   int i = 0;
   float f = 0.0f;
   System.out.print("Enter integer:");    
   if (scan.hasNextInt()) {
       // Judge whether the input is an integer
       i = scan.nextInt();        // Receive integer
       System.out.println("Integer data:" + i);    
       } else {
       // Enter wrong information
       System.out.println("The input is not an integer!");  
       }
   System.out.print("Enter decimal:");    
   if (scan.hasNextFloat()) {        
   // Judge whether the input is decimal
       f = scan.nextFloat();        // Receive decimal
       System.out.println("Decimal data:" + f);    
       } else {
       // Enter wrong information
       System.out.println("The input is not a decimal!");  
       }
   scan.close();
}

Sequential structure

The basic structure of JAVA is sequential structure. Unless otherwise specified, it will be executed sentence by sentence in order. Sequential structure is the simplest algorithm structure.

It is composed of several statements in sequence, and it is basically processed from the box to the next algorithm.
The embodiment of sequential structure in the program flow chart is to connect the program frame from top to bottom with flow lines and execute the algorithm steps in sequence.

Select structure

if single selection structure

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

if double selection structure

if(Boolean expression){
  //If the Boolean expression has a value of true}else{
  //If the value of the Boolean expression is false}

Meaning: when the conditional expression is true, execute statement block 1; otherwise, execute statement block 2. That is the else part

if multiple selection structure

if(Boolean expression    1){
  //If the value of Boolean expression 1 is true, execute the code 
  }else if(Boolean expression    2){
  //If the value of Boolean expression 2 is true, execute the code 
  }else if(Boolean expression    3){
  //If the value of Boolean expression 3 is true, execute the code 
  }else {
  //If none of the above Boolean expressions is true, execute the code 
}

If statements can be followed by else if... Else statements, which can detect a variety of possible situations.

  • Note the following:
    •  if There must be at most one statement else sentence, else Statement in all else if After the statement. 
      
    •  if There can be several statements else if Statements, they must be else Before the statement.
      
    •  Once one of them else if Statement detected as true,other else if as well as else Statements will skip execution.
      

Nested if structure

It is legal to use nested if... Else statements. That is, you can use an if or else if statement in another if or else if statement. You can nest else if like an IF statement else.

if(Boolean expression    1){
  //If the value of Boolean expression 1 is true, execute the code 
  if(Boolean expression    2){
     //If the value of Boolean expression 2 is true, execute the code
  }
}

switch multiple selection structure

switch(expression){
   case value :
      //sentence
      break; //Optional
   case value :
      //sentence
      break; //Optional
   //You can have any number of case statements
   default : //Optional
      //sentence 
}

Statement rules of switch case:

The switch case statement has the following rules:

  • The variable type in the switch statement can be byte, short, int or char. Starting from Java SE 7, switch supports String type, and the case label must be a String constant or literal.
    • Here you can use IDEA to decompile and view the details
    • Find the corresponding class file in the out folder
    • Copy to the current folder and open it in IDEA to view
  • A switch statement can have multiple case statements. Each case is followed by a value to compare and a colon.
    The data type of the value in the case statement must be the same as that of the variable, and can only be a constant or literal constant.
  • When the value of the variable is equal to the value of the case statement, the statement after the case statement starts to execute, and the switch statement will not jump out until the break statement appears.
  • When a break statement is encountered, the switch statement terminates. The program jumps to the statement execution after the switch statement. Case statements do not have to contain break statements. If no break statement appears, the program will continue to execute the next case statement until the break statement appears.
  • A switch statement can contain a default branch, which is generally the last branch of the switch statement (it can be anywhere, but it is recommended to be in the last branch). Default is executed when the value of no case statement is equal to the value of the variable. The default branch does not require a break statement.

Cyclic structure

If you want to perform the same operation multiple times, you need to use the loop structure.

There are three main loop structures in Java:
while loop
do... while loop
for loop
An enhanced for loop is introduced in Java 5, which is mainly used for arrays.

while Loop

At the beginning of the loop, calculate the value of "Boolean expression" once. If the condition is true, execute the loop body.
For each additional cycle later, it will be recalculated before starting to judge whether it is true.
Until the condition does not hold, the cycle ends.

while( Boolean expression    ) {  
	//Loop content
}
  • In most cases, we will stop the loop. We need a way to invalidate the expression to end the loop.

    ​ The methods are: circular internal control and external flag setting! etc.

  • If the loop condition is always true, it will cause infinite loop [dead loop]. We should try to avoid dead loop in normal business programming. It will affect the program performance or cause the program to get stuck and run away!

do...while loop

For the while statement, if the condition is not met, it cannot enter the loop. But sometimes we need to perform at least once even if the conditions are not met.
The do... While loop is similar to the while loop, except that the do... While loop is executed at least once.

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

Note: the Boolean expression follows the loop body, so the statement block has been executed before detecting the Boolean expression.
If the value of the Boolean expression is true, the statement block executes until the value of the Boolean expression is false.

  • Difference between While and do While:

    While is judged before execution. Do while is to execute first and then judge!
    Do...while always ensures that the loop is executed at least once! This is their main difference.

For loop

for loop statement is a general structure that supports iteration. It is the most effective and flexible loop structure.
The number of times the for loop is executed is determined before execution.

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

There are the following explanations for the for loop:

  • Perform the initialization step first. You can declare a type, but you can initialize one or more loop control variables or empty statements.
  • Then, the value of the Boolean expression is detected. If true, the loop body is executed. If false, the loop terminates and starts executing the statement after the loop body.
  • After executing a loop, update the loop control variable (the iteration factor controls the increase or decrease of the loop variable). Detect the Boolean expression again. Loop through the above procedure.

The for loop simplifies the code and improves readability when the number of cycles is known.
We usually use the for loop most!

break & continue

break

break is mainly used in loop statements or s switch statements to forcibly jump out of the whole statement block.
break jumps out of the innermost loop and continues to execute the following statements of the loop.

Jump out of loop:

public static void main(String[] args) {    
	int i=0;
   while (i<100){        
   	i++;
		System.out.println(i);        
		if (i==30){
      	break;      
   	}
 	} 
}

continue

continue applies to any loop control structure. The function is to make the program skip this cycle and jump to the iteration of the next cycle.
In the for loop, the continue statement causes the program to immediately jump to the update statement.
In the while or do... While loop, the program immediately jumps to the judgment statement of Boolean expression.

public static void main(String[] args) {    
	int i=0;
   while (i<100){        
   	i++;
      if (i%10==0){
           System.out.println();            
           continue;
      }
       System.out.print(i);  
   }
}

The difference between the two

Break in the main part of any loop statement, you can use break to control the flow of the loop. Break is used to forcibly exit the loop without executing the remaining statements in the loop. (break statements are also used in switch statements)

The continue statement is used in the body of a loop statement to terminate a loop process, that is, skip the statements that have not been executed in the loop body, and then determine whether to execute the loop next time.

continue with label

[understand]

  1. Goto keyword has long appeared in programming languages. Although goto is still a reserved word of Java, it has not been officially used in the language; Java has no goto. However, in the two keywords break and continue, we can still see some shadow of goto - labeled break and continue.

  2. "label" refers to the identifier followed by a colon, for example: label:

  3. For Java, the only place where tags are used is before loop statements. The only reason to set the label before the loop is that we want to nest another loop in it. Because the break and continue keywords usually only break the current loop, but if they are used with the label, they will break to the place where the label exists.

  4. Examples of labeled break and continue:

    [demonstration: print all prime numbers between 101-150]

    public static void main(String[] args) {    
    	int count = 0;
       //Make a mark here, outer
       outer: for (int i = 101; i < 150; i ++) {   
          //If a number cannot be obtained by multiplying a number within half of itself by another number, then it is a prime number
       	for (int j = 2; j < i / 2; j++) {            
       		if (i % j == 0)
                //Here, it returns to the external loop through the marker of outer
             	continue outer;      
          }
          System.out.print(i+ "  ");  
       }
    }
    

practice

The sum of odd and even numbers between 0 and 100

public static void main(String[] args) {    
   int oddSum = 0;  //Used to hold the sum of odd numbers
   int evenSum = 0;  //Used to store even numbers and
   for(int i=0;i<=100;i++){
       if(i%2!=0){
           oddSum += i;        
       }else{
           evenSum += i;      
       }
 	}
   System.out.println("Odd sum:"+oddSum);    
   System.out.println("Even sum:"+evenSum);
}

The number between 1 and 1000 that can be divided by 5, and 3 are output per line

public static void main(String[] args) {    
   for(int i = 1;i<=1000;i++){
       if(i%5==0){
           System.out.print(i+"\t");      
       }
       if(i%(5*3)==0){
           System.out.println();      
       }
 	} 
}

Print 99 multiplication table

for (int i = 1; i <= 9 ; i++) {    
   for (int j = 1; j <= i; j++) {
       System.out.print(j + "*" + i + "=" + (i * j)+ "\t");  
   }
   System.out.println(); 
}

Print triangles

//The outer loop controls the line
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("*");
   }
   //Here, use < to output a left triangle smaller than the left
   for(int j = 1; j < i; j++){
      System.out.print("*");
   }
}

Enhanced for loop

Java 5 introduces an enhanced for loop, which is mainly used for arrays or collections, to simplify the code.
The syntax format of Java enhanced for loop is as follows:

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

Declaration statement: declare a new local variable. The type of the variable must match the type of the array element. Its scope is limited to the circular statement block, and its value is equal to the value of the array element at this time.
Expression: an expression is the name of the array to be accessed, or a method whose return value is an array.

public static void main(String[] args) {    
   int [] numbers = {10, 20, 30, 40, 50};    
   for(int x : numbers ){
      System.out.print( x );        
      System.out.print(",");  
   }
   System.out.print("\n");
   String [] names ={"James", "Larry", "Tom", "Lacy"};    
   for( String name : names ) {
      System.out.print( name );        
      System.out.print(",");  
   }
}

Tags: Java

Posted by jnoun on Tue, 19 Apr 2022 05:15:46 +0930