Java basic syntax

Posted by scottbarry on Sat, 26 Feb 2022 16:57:59 +0100

Basic Java syntax (2)

The wood that embraces is born at the slightest; The nine storey platform starts from the tired soil; A journey of a thousand miles begins with a single step—— Tao Te Ching

10, Scanner class (user interaction data type)

  1. From Java 5 to Java util. Scanner is a package. We can get user input through scanner.

  2. Basic syntax:

    import java.util.Scanner;	//Using Scanner requires a pilot package
    	......
    	Scanner scanner = new Scanner(System.in);
    
  3. Get the input string through the next() and nextLine() methods of Scanner class. Generally, you need to use hasNext() or hasNextLine() to judge whether there is still input data before reading.

    next():
    1.Be sure to read valid characters before you can end the input.
    2.For spaces encountered before entering valid characters, next()Method automatically removes it.
    3.Only after entering a valid character will the blank space after it be used as the separator or terminator.
    4.next()Cannot get string with space!
    
    nextLine():
    1.with Enter Is the terminator, i.e nextLine()Method returns all characters before entering carriage return.
    2.nextLine()Can get blank!
    
  4. After using up Scanner (or other IO stream classes), if you don't close it, it will always occupy resources, so it's a good habit to close it after using it.

    Close Scanner:

    	Scanner s = new Scanner(System.in);
    	......
        s.close();	//Close Scanner
    
  5. Advanced use of Scanner.

    hasNext()		:The string used to check whether there is any input
    next() 			:String used to accept console input
    
    hasNextInt()	:Integer used to check whether there is any input
    nextInt() 		:Integer used to accept console entry
    
    hasNextFloat()	:Used to check whether there are any floating-point numbers entered
    nextFloat() 	:Used to accept floating-point numbers entered by the console
    
    hasNextDouble()	:Used to check whether there are any floating-point numbers entered
    nextDouble() 	:Used to accept floating-point numbers entered by the console
    
    

Among them, the functions of hasNextFloat() and hasNextDouble() are basically the same, but in particular, when the console inputs either a decimal or an integer, the results of these two methods return true, and the entered integer will be changed into a decimal.

hasNextInt() returns true only when an integer is entered on the console.

import java.util.Scanner;

public class demo01 {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int i = 0;
        double d = 0.0;

        if(scanner.hasNextInt()){
            i = scanner.nextInt();
            System.out.println("i = "+i);
        }else{
            System.out.println("The input is not an integer!");
        }

        if(scanner.hasNextDouble()){
            d = scanner.nextDouble();
            System.out.println("d = "+d);
        }else{
            System.out.println("The input is not a decimal!");
        }

        scanner.close();
    }
}
Three results of the above code:
1.Enter integer:
20				//keyboard entry
i = 20
20				//keyboard entry
d = 20.0

2.Enter decimal:
3.14			//keyboard entry
 The input is not an integer!
d = 3.14

3.Input string (non numeric)
hello			//keyboard entry
 The input is not an integer!
The input is not a decimal!

Result analysis:

1. Enter an integer:

When the first 20 is entered, because the input is an integer, the first 20 is scanned Nextint() receives and assigns a value to i and outputs i = 20.

The program scanner Hasnextdouble() waits for the console to input again, so the second 20 is input again and is scanned by scanner Nextdouble() receives and assigns a value to D and outputs d = 20.0.

2. Enter decimal:

When entering 3.14, it cannot be scanned because it is not an integer Nextint() receives and assigns a value, so it outputs "input is not an integer!".

Since the input 3.14 has not been received, it will continue to be sent to scanner Nextdouble() judge and receive.

3. Input string:

When entering the string hello, it is not used by scanner in the whole program Nextint() was not received by scanner Nextdouble() received.

Cause analysis:

Why enter an integer, scanner Nextdouble() returns true and converts an integer to a decimal of type double?

That's right for scanner Analyze the source code of nextdouble(). (hold down Ctrl + click the scanner.nextDouble() method of the source program to view the source code)

Double.parseDouble() is to change the contents of String type in parentheses into double type.

In other words, when we input the integer 20 on the console, it will be converted into a String type and assigned to s in the program, and then through double Parsedouble() is to change the String s of String type in parentheses into double type and then return it, so the integer 20 is converted into 20.0 of double type.

Why enter a string, scanner Nextdouble() returns false?

This is because catch throws a NumberFormatException (number formatting exception) in the source code. Check that the string is mixed with string or other types. When you enter a string, false is returned. Therefore, when we use the console to manually input the decimal, we cannot add F or D after the decimal, otherwise an error will be reported. However, it is OK to define numbers in the program.

11, Random number class random (reference data type) (Extended)

Random class, which can generate random numbers of various data types. Here we mainly introduce the way to generate integers and decimals.

  • public int nextInt(int maxValue) generates random integers in the range of [0,maxValue), including 0 and excluding maxValue;

  • public double nextDouble() generates random decimals in the range of [0,1], including 0.0 and excluding 1.0.

//How to use Random
import java.util.Random;	//Guide Package

......
    //Random variable name = new Random();
    Random r = new Random();

example:

import java.util.Random;

public class RandomDemo {
	public static void main(String[] args) {
		// Create an instance of the Random class
		Random r = new Random(); 
		// Obtain the random integer in the range of 0-100, and assign the generated random integer to the i variable
		int i = r.nextInt(100); 
		//Obtain the random decimal within the range of 0.0-1.0, and assign the generated random decimal to the d variable
		double d = r.nextDouble(); 
		System.out.println(i); 
		System.out.println(d); 
	}
}

12, Sequential structure

  • Java includes sequential structure, selection structure and loop 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.

13, Select structure

(1) if conditional statement

  • If statement can judge the result of the expression alone, and carry out some processing if certain conditions are met.

  • Syntax:

    if(Boolean expression){
        //Statement executed if the expression is true
    }
    
  • Illustration:

  • example:

    	int a = 10;
    	
    	if(a > 10){
    		return true;
    	}
    	return false
    

(2) if... else conditional statement

  • If statement can be followed by else statement. Else statement block will be executed only when Boolean expression value of if statement is false.

  • Syntax:

    if(Boolean expression){
        ......
       //Statement executed if the value of the Boolean expression is true
    }else{
        ......
       //Statement executed if the value of Boolean expression is false
    }
    
  • Illustration:

  • example:

    	int a = 10;
    	int b = 11;
    
    	if(a >= b){
    		System.out.println("a >= b");
    	}else{
        System.out.println("a < b");	
        }
    

(3) If... else if... Multi branch statement

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

  • When using if, else, if and else statements, you should pay attention to the following points:

    1. An IF statement can have at most one else statement, which follows all else if statements.
    2. An IF statement can have several else if statements, which must precede the else statement.
    3. Once one else if statement is detected as true, the other else if and else statements will skip execution.
  • Syntax:

    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
    }
    
  • Illustration:

  • example:

    public class Test {
       public static void main(String args[]){
          int grade = 80;
     
          if(grade >= 85){
             System.out.print("excellent");
          }else if(gradegrade >= 75){
             System.out.print("good");
          }else if(grade >= 60){
             System.out.print("pass");
          }else{
             System.out.print("fail,");
          }
       }
    }
    

(4) Nested if conditional statements

  • 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.

  • Syntax:

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

    public class Test {
     
       public static void main(String args[]){
          int x = 30;
          int y = 10;
     
          if( x == 30 ){
             if( y == 10 ){
                 System.out.print("X = 30 and Y = 10");
              }
           }
        }
    }
    

(5) switch multiple selection structure

  • The switch case statement determines whether a variable is equal to a value in a series of values. Each value is called a branch.

  • Syntax:

    switch(expression){
        case value1:
                ...		//Execute statement
                break;	//Optional
        case value2:
                ...		//Execute statement
                break;	//Optional
        ......
            
        default:
            ...   		//Execute statement     
    }
    
  • The switch case statement has the following rules:

    1. 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.
    2. A switch statement can have multiple case statements. Each case is followed by a value to compare and a colon.
    3. 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.
    4. 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.
    5. 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.
  • example:

    public class Test {
       public static void main(String args[]){
          int i = 1;
          switch(i){
             case 0:
                System.out.println("0");
             case 1:
                System.out.println("1");
             case 2:
                System.out.println("2");
             case 3:
                System.out.println("3"); break;
             default:
                System.out.println("default");
          }
       }
    }
    
    /*
    Output is:
    1
    2
    3
    */
    
    

14, Cyclic 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.

(1) while loop statement

  • The while statement will repeatedly judge the condition. As long as the condition is true, the statement in {} will be executed until the condition is not true, and the while loop will end.

  • Syntax:

    while( Boolean expression ) {
      //Cyclic content
    }
    
  • Illustration:

  • example:

    public class Test {
       public static void main(String[] args) {
          int x = 1;
          while( x < 4 ) {
             System.out.println("x = " + x );
             x++;
          }
       }
    }
    
    /*Output:
    x = 1
    x = 2
    x = 3 */
    

(2) do... while loop statement

  • The do... While loop is similar to the while loop, except that the do... While loop is executed at least once.
  • Syntax:
do {
       //Code statement
}while(Boolean expression);

**Note: * * the Boolean expression is after 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.

  • Illustration:

  • example:

    public class Test {
       public static void main(String[] args){
          int x = 4;
     
          do{
             System.out.println("x = " + x );
             x-;
          }while( x > 0 );
       }
    }
    /*Output:
    x = 4
    x = 3
    x = 2
    x = 1  */
    

(3) for loop

  • The number of times the for loop is executed is determined before execution. The syntax format is as follows:
for(initialization; Boolean expression; Operation expression) {
    //Code statement
}
  • Specific implementation process:

    for(one;two;three){
        four;
    }
    /*
    Step one, execute
     Step 2: execute two
     Step 3: execute four
     Step 4: execute three, and then repeat step 2
     Step 5: exit the cycle
    */
    
  • example:

    public class Test {
       public static void main(String[] args) {
     
          for(int x = 1; x < 4; x++) {
             System.out.println("x = " + x );
          }
       }
    }
    
    /*Output:
    x = 1
    x = 2
    x = 3	*/
    

(4) Enhanced for loop

  • Java 5 introduces an enhanced for loop that is mainly used for arrays or collections.

  • Syntax:

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

    **Declaration statement: * * declare a new local variable whose type must match the type of 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: * * expression is the name of the array to be accessed or the method whose return value is array.

  • example:

    public class Test {
       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(",");
          }
       }
    }
    
    /*Output:
    10,20,30,40,50,
    James,Larry,Tom,Lacy,
    */
    

15, Jump statement

In the Java language, there are three kinds of jump statements: break, continue and return.

(1) break statement

  • break is mainly used in loop statements or switch statements to end the whole loop or jump out of the whole statement block.

  • When multiple loops are nested, break jumps out of the innermost loop of the loop.

    public class Test {
        public static void main(String[] args) {
    
            for (int i = 1 ;i <4;i++){
                for (int a = 4;a > 0;a--){
                    if(a == 2){
                        break;
                    }
                    System.out.print(a + " ");
                }
            }
        }
    }
    
    /*output
    4 3 4 3 4 3
    */
    

(2) continue statement

  • continue applies to any loop control structure. The function is to make the program immediately terminate this cycle and directly determine the next cycle.

    In the for loop, the continue statement causes the program to immediately jump to the operation expression statement.

    In the while or do... While loop, the program immediately jumps to the judgment statement of Boolean expression.

  • example:

    public class Test {
       public static void main(String[] args) {
          int [] numbers = {10, 20, 30, 40, 50};
     
          for(int x : numbers ) {
             if( x == 30 ) {
            continue;
             }
             System.out.println( x );
          }
       }
    }
    /*Output:
    10
    20
    40
    50
    */
    

(3) return statement

  • The return statement can return from a method and give control to the statement that calls it.

(4) About break and continue with labels (extension, not recommended)

  • The only place where Java uses labels is before the loop statement, and the reason for setting labels before the loop statement:

    When the break or continue statement appears in the nested loop, it can only jump out of the inner loop. If you want to use the break or continue statement to jump out of the outer loop, you need to add a label to the outer loop, and they will break to the place of the label.

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

        outer:for (int i = 1 ;i <4;i++){
            for (int a = 4;a > 0;a--){
                if(a == 2){
                    break outer;	//End the cycle of the specified label
                }
                System.out.print(a + " ");
            }
        }
    }
}

/*output
4 3
*/
  • break with label: end the loop of the specified label.
  • continue with label: end the loop of the specified label.

Topics: Java Back-end