The way of Java learning week2

Posted by jazzydog on Sun, 09 Jan 2022 15:42:20 +0100

The way of Java learning week2

Move towards the goal of Java programmers!

day5

Keyboard data entry exercise

Exercise 1: enter two data on the keyboard, sum the two data, and output the results

//Guide Package
import java.util.Scanner ;

class ScannerTest2{
    public static void main(String[] args){
        //Create a keyboard entry object
        Scanner sc = new Scanner(System.in) ;
        
        //Prompt and enter data
        System.out.println("Please enter the first data:") ;
        int a = sc.nextInt() ;
        
        System.out.println("Please enter the second data:") ;
        int b = sc.nextInt() ;
        
        
        
        //Find the sum of two numbers
        int c = a+b ;
        System.out.println("The sum of the two numbers is:"+c) ;
    }
}

Exercise 2: enter two data with the keyboard and obtain the maximum value of the two data

//Guide Package
import java.util.Scanner ;

class ScannerTest2{
    public static void main(String[] args){
        //Create keyboard entry object
        Scanner sc = new Scanner(System.in) ;
        
        //Prompt and enter data
        System.out.println("Please enter the first data:") ;
        int a = sc.nextInt() ;
        
        System.out.println("Please enter the second data:") ;
        int b = sc.nextInt() ;
        
        
        
        //Find the maximum of the two numbers
        System.out.println("The maximum value of the two numbers is:"+((a>b)?a:b)) ;
    }
}

Exercise 3: enter three data on the keyboard to find the maximum value

//Guide Package
import java.util.Scanner ;

class ScannerTest3{
    public static void main(String[] args){
        //Create keyboard entry object
        Scanner sc = new Scanner(System.in) ;
        
        //Prompt and enter data
        System.out.println("Please enter the first data:") ;
        int a = sc.nextInt() ;
        
        System.out.println("Please enter the second data:") ;
        int b = sc.nextInt() ;
        
        System.out.println("Please enter the third data:") ;
        int c = sc.nextInt() ;
        
        
        
        //Find the maximum of three numbers
        //Method 1: define intermediate variables (recommended)
        int temp = (a>b)?a:b ;
        int max = (temp>c)?temp:c ;
        System.out.println("The maximum of the three data is:"+max) ;
        
        System.out.println("---------------------------------------") ;
        //Method 2: nesting of ternary operators (not recommended)
        
        int max2 = (a>b)?((a>c)?a:c):((b>c)?b:c) ;
        System.out.println("The maximum of the three data is:"+max2) ;
    }
}

Exercise 4: enter two data on the keyboard and compare whether the two data are equal

//Guide Package
import java.util.Scanner ;

class ScannerTest4{
    public static void main(String[] args){
        
        //Create keyboard entry object
        Scanner sc = new Scanner(System.in) ;
        
        //Prompt and enter data
        System.out.println("Please enter the first data:") ;
        int a = sc.nextInt() ;
        
        System.out.println("Please enter the second data:") ;
        int b = sc.nextInt() ;
        
        
        
        //Compare whether the two data are equal
        //Mode 1
        boolean flag = (m==n)?true:false ;
        System.out.println(flag) ;
        
        //Improvement of mode 1 - since = = itself is comparison, mode 1 can be abbreviated
        boolean flag = m==n ;
        System.out.println(flag) ;
        
        //Method 2: process control statement (start next)
    }
}

Through the above exercises, we are familiar with the use of operators, but in some places, we can actually use more readable and powerful ways to implement them, so next we begin to learn process control statements.

Process control statement

Process control statements are divided into sequential structure statements, selection structure statements and circular structure statements.

Sequential structure statement

The sequential structure statement is the simplest process control in the program, and the code is loaded from top to bottom (HelloWorld written at the beginning of learning is the sequential structure statement).

Sequence structure diagram

Next, write a program to test:

//The JVM loads this class
class ShunXuDemo{
    
    //The main method is the entry of the program and needs to be called by the JVM
    public static void main(String[] args){
        
        System.out.println("The program begins...") ;
        System.out.println("Hello Java!!!") ;
        System.out.println("The program is over...") ;
        int a = 100 ;
        System.out.println("over"+a) ;
    }
}

Select structure statement

Selection structure is also called branch structure. The code should judge according to conditions (logical operation) to produce two choices. The code executes different codes according to different choices.

Java provides if statements and switch statements

Select if statement of structure

The if statement has three formats, which we will learn in turn

if statement format 1:

	if(Conditional expression){
		sentence ;
	}

Execution process:

  1. If the current conditional expression holds, execute the statement
  2. Otherwise, the statement will not be executed
//Guide Package
import java.util.Scanner ;

class IfDemo{
	
	public static void main(String[] args){
		
		//Create keyboard entry object
		Scanner sc = new Scanner(System.in) ;
		
		//Prompt and enter data
		System.out.println("Please enter a data x Value of:") ;
		int x = sc.nextInt() ;
		
		if(x<10){
			System.out.println("x Less than 10, the value is:"+x) ;
		}
		//if()...
		
		System.out.println("over") ;
	}
}

Application scenario of format 1: judge for a single condition

matters needing attention:

  1. The result of a relational expression must be Boolean
  2. If the statement body of the if structure is a statement, braces can be omitted; If there are multiple statements, they cannot be omitted. It is recommended that braces should never be omitted.
  3. Generally speaking, there is no semicolon when there is a left brace, and there is no left brace when there is a semicolon.

if statement format 2:

	if(Conditional expression){
		Statement 1 ;
	}else{
		Statement 2 ;
	}

Execution process:

  1. Judge whether the conditional expression is true. If it is true, execute statement 1
  2. If not, execute statement 2
/*
	Demand: judge the maximum of the two numbers
*/

//Guide Package
import java.util.Scanner ; 

class IfDemo2{
		
		public static void main(String[] args){
			
			//Create keyboard entry object
			Scanner sc = new Scanner(System.in) ;
			
			//Prompt and enter data
			System.out.println("Please enter the first data:") ;
			int a  = sc.nextInt() ;
			
			System.out.println("Please enter the second data:") ;
			int b  = sc.nextInt() ;
			
			//Compare the maximum of the two data
			//Define result variables
			int max ;
			if(a>b){
				//System.out.println("max." + a)// Output statement
				max = a ; //Assign a max
			}else{
				max = b ; //Assign b max
			}
			
			System.out.println("The maximum of the two data is:"+max) ;
			
		}
}

Application scenario of format 2: judge for two situations

Nesting method of if format 2:

if(expression){
    if(Expression 1){
        Statement 1 ;
    }else{
        Statement 2 ;
    }
}else{
    if(Expression 2){
        Statement 3 ;
    }else{
        Statement 4 ;
    }
}

Execution process:

  1. First judge whether the expression is true. If it is true

  2. Execute the if statement inside
    2.1 judge whether expression 1 is true. If it is true, execute statement 1
    2.2 if not, execute statement 2

  3. If the comparison expression is not valid for the first time, execute the if statement in else

    3.1 judge whether expression 2 is true. If it is true, execute statement 3
    3.2 if not, execute statement 4

if format 2 exercise: simulate user login operation

Requirements:

  1. Assume that the user name and password (impersonation database) already exist

  2. Enter the user name and password (String type) on the keyboard

    Determine whether the user name and password match

  3. If it matches, you will be prompted with "Congratulations, login succeeded!"; If there is no match, you will be prompted with "sorry, wrong user name or password!".

Methods involved:

  1. The Scanner class provides a method:
    public String nextLine(): enter String type data

  2. Functions in String type:
    equals(String other): compare whether the contents of two strings are the same

//Guide Package
import java.util.Scanner ;

class IfTest{
	public static void main(String[] args){
		
		//demand
		//Assume that the user name and password (impersonation database) already exist
		
		String name = "admin" ; //String is a special reference type (described later in common classes)
		String pwd = "admin" ;
		
		//Create a keyboard entry object and prepare to enter user name and password
		Scanner sc = new Scanner(System.in) ;
		
		//Prompt and enter data
		System.out.println("Please enter your user name:") ;
		//public String nextLine(): enter String type data
				//Variable name = fixed format: keyboard entry object nextLine() ;
		String username = sc.nextLine() ;
		
		System.out.println("Please enter your password:") ;
		String password = sc.nextLine() ;
			
		//Judge
		//We use the known user name and password to compare with the entered user name and password
		/*
			String Function in type: equals(String other)
			Compare whether the two string contents are the same
		*/
		if(name.equals(username) && pwd.equals(password)){ //agreement
		
			//establish
			System.out.println("Congratulations, login succeeded!");
			
		}else{
			//Not established
			System.out.println("Sorry, your user name or password is wrong!");
		}
	}
}

Note: the difference between if statement format 2 and ternary operator

  1. if... else can not only manipulate specific values, but also nest statements; Ternary operators cannot nest statements
  2. if... else can have no return value. The ternary operator needs a return value after operation
  3. Ternary operators can be converted into if... else structures. If... else structures can not be converted into ternary operators

if statement format 3:

	if(Expression 1){
		Statement 1 ;
	}else if(Expression 2){
        Statement 2 ;
    }else if(Expression 3){
        Statement 3 ;
        ...
        ...
    }else{
        sentence n ;
    }

Execution process:

  1. Judge whether expression 1 is true. If it is true, execute statement 1;
  2. If expression 1 is not true, continue to judge whether expression 2 is true. If it is true, execute statement 2;
  3. If expression 2 is not true, continue to judge whether expression 3 is true. If true, execute statement 3;
  4. Repeat the judgment similar to 3 (just change the number) until it is judged that the above conditional expressions are not valid (that is, the corresponding else is encountered), then execute the statement n in else
/*
Requirements:
		Enter a student's grade on the keyboard: (no prompt for data type, int type to receive)
				
				90~100  "Excellent“
				80~90   "Better“
				70~80   "Good“
				60~70   "Pass“
				60 The following "fail"
*/

//Guide Package
import java.util.Scanner ;

class IfDemo3{
	
	public static void main(String[] args){
			
        //Create a keyboard entry object
        Scanner sc = new Scanner(System.in) ;

        //Prompt and enter data
        System.out.println("Please enter the student's grade:") ;
        int socre = sc.nextInt() ;

        //Judge according to the above requirement format
        if(socre>100 || socre<0){
            //Error data prompt
            System.out.println("I'm sorry,invalid data!") ;
        }else if(socre>=90 && socre<=100){
            System.out.println("Excellent results") ;
        }else if(socre>=80 && socre<90){
            System.out.println("Good results") ;
        }else if(socre>=70 && socre<80){
            System.out.println("Good results") ;
        }else if(socre >=60 && socre<70){
            System.out.println("Pass the grade") ;
        }else{
            System.out.println("fail,") ;
        }
	}
}

matters needing attention:

Q: What data should we enter when testing the program?

A: Three types of data should be entered during the test:

		  1. Bad data (negative number),Or out of range data,All belong to"invalid data")
		  2. Correct data (data in range)
		  3. Boundary data (critical value)

Application scenario of format 3: judge for various situations. Generally, format 3 is rare in business logic under development!

Select the switch statement of the structure

Format:

	switch(expression){
        case Value 1:
            Statement 1 ;
            break ;
        case Value 2:
            Statement 2 ;
            break ;
        ...
        ...
        ...
        default:
            sentence n ;
            break ;
    }

Execution process:

  1. Judge whether the value of the expression matches the case value 1. If the matching is successful, execute statement 1 and exit the judgment through break
  2. If the case value 1 does not match, continue to compare with the case value 2 after the case. If it matches, execute statement 2 and exit the judgment through break
  3. And so on, until the value of the above case does not match the result of the expression in switch, execute the statement n in default.
  4. Finally, if the program is executed to the end by default, it will end automatically, otherwise it will end through break
/*
	Requirements:	
		Enter a value week on the keyboard to output the "day of the week"
		week It's 1, that's "Monday"; 2, is "Tuesday"; 3. It's "Wednesday" Until Sunday.
*/

//Guide Package
import java.util.Scanner ;

class SwitchDemo{
	public static void main(String[] args){
		
		//Create a keyboard entry object
		Scanner sc = new Scanner(System.in) ;
		
		//Prompt and enter data
		System.out.println("Please enter a data week:") ;
		int week = sc.nextInt() ;
	
		switch(week){
		case 1:
			System.out.println("Monday") ;
			break ;
		case 2:
			System.out.println("Tuesday") ;
			break ;
		case 3:
			System.out.println("Wednesday") ;
			break ;
		case 4:
			System.out.println("Thursday") ;
			break ;
		case 5:
			System.out.println("Friday") ;
			break ;
		case 6:
			System.out.println("Saturday") ;
			break ;
		case 7:
			System.out.println("Sunday") ;
			break ;
		default :
			System.out.println("I'm sorry,invalid data!") ;
			break ;
		}
	}
}

matters needing attention:

  1. The data types of expressions in switch statements can be byte, short, int and char, enum after JDK5 and String after JDK7.

  2. The value after case can only be a constant, not a variable. Moreover, the values after multiple cases cannot be the same.

  3. default can be omitted only when the judgment value is fixed, otherwise it is generally not recommended to omit.

  4. The break in the case statement must be carried, otherwise it will cause case penetration (described separately below); If the default statement is at the end of the data, break can be omitted (not recommended).

  5. default can appear anywhere in a switch statement.

  6. default is executed only when there is no match in the current case.

  7. There are two end conditions for switch:

    a. break end

    b. The program executes to the end by default

Application scenario of switch statement: judgment on several constant values

Supplement:

  • case penetration

    In the switch statement, if break is not written after the case, penetration will occur, that is, the program will not judge the value of the next case and run down in sequence until the break statement is encountered or the switch is executed.

    Here are some examples:

class SwitchDemo2{
    
    public static void main(String[] args){
        int i = 5 ;
        switch(i){
            case 0:
                System.out.println("implement case0") ;
                break ;
            case 5:
                System.out.println("implement case5") ;
            case 10:
                System.out.println("implement case10") ;
            default:
                System.out.println("implement default") ;
        }
    }
}

After the above program executes case 5, because there is no break statement to stop the program, the program will execute sequentially until the end of the switch structure.

class SwitchDemo3{
	
	public static void main(String[] args){
		
        int x = 3 ;
		int y = 4 ;
		switch(x){//3
		default :
			y++ ;//4+1 = 5 
		case 4:
			y++ ;//5+1 = 6 
		case 5 :	
			y++ ;//6+1 = 7
		}
		System.out.println("y:"+y) ;
    }
}

The above program first judges x, jumps to default and executes after there is no match. Since there is no break statement to stop the program, the program will execute in sequence, and the value of y will increase in sequence according to the execution until the end of the switch structure.

class SwitchDemo4{
	
	public static void main(String[] args){
		
        int a = 3 ;
		int b = 4 ;
		switch(a){//3
			default :
				b++ ;//3+1 = 4
				break ;
			case 4:
				b++ ;
			case 5: 
				b++;
		}
        System.out.println("b:"+b) ;
    }
}

The above program first judges that a does not match, then jumps to default and executes. y has a break statement to stop the program, so b ends the switch statement after self increment once, and the value output of b is 4.

class SwitchDemo5{
	
	public static void main(String[] args){
		
        int a = 3 ;
		int b = 4 ;
		switch(a){//a=3
		
			case 3:
				b++ ;//4+1 = 5
			case 5: 
				b++ ;//5+1 = 6
			default :
				b++ ;//6+1 = 7
				break ;
		}
        System.out.println("b:"+b) ;
    }
}

The above program first judges a and starts execution after case 3 matches. Since there is no break statement to stop the program, the program will execute in sequence, and the value of b will increase in turn according to the execution until a break is encountered. The value of b is 7.

day6

Process control statements - continued

Circular structure statement

Loop statement is to repeatedly do one thing (repeatedly execute a piece of code) under specific circumstances (meeting the loop conditions). These repeatedly executed codes are called loop body statements.

Loop structure statements are divided into for loop, while loop and do while loop.

for loop of loop structure

Format:

	for(Initialization statement a;Conditional expression b;Control body statement (also known as step statement) d){
        Loop body statement;c
    }

Execution process:

  • Execution sequence: abcd - > BCD - > BCD... Until b is not satisfied.
  • a is responsible for initializing loop variables
  • b. judge whether the cycle conditions are met
  • c is a statement executed in a loop
  • d be responsible for controlling the change of cyclic variables
/*
	Requirements:
		You need to output 10 sentences of "Hello world" on the dos console
*/

class ForDemo{
	public static void main(String[] args){
		
		for(int x = 1 ;x <= 10 ; x ++)
			System.out.println("HelloWorld") ;
		}
	}
}

matters needing attention:

If a loop statement is a statement, braces can be omitted; If a circular sentence is more than one sentence, curly braces cannot be omitted. It is recommended never to omit them.

Application scenario of for loop: when specifying the number of loops, the for loop is preferred.

Supplement:

  • Another way to use the for loop (dead loop):
	for(;;){
        Loop body statement ;
        if(Conditional expression){
            break ;//When a condition is met, the break statement is used to break the loop
        }
    }
while loop of loop structure

Format: while has two types: basic format and extended format

	//Basic format
	while(Conditional expression){
        Loop body statement ;
    }
	//Extended format
	Initialization statement ;
	while(Conditional expression){
        Loop body statement ;
        Control body statement ;
    }

Execution process:

  1. Initialization statement for assignment
  2. Judge whether the conditional expression is true
  3. If true, execute the loop body statement and control body statement
  4. Continue to execute 2 and 3 until the conditional expression does not hold and exit the loop

The flowchart is the same as the execution flowchart of the for loop and is omitted here

Application scenario of while loop: if the number of loops is not clear, use while loop.

Supplement:

  • Relationship and difference between while loop and for loop:

Connection: both can describe the idea of loop and optimize the code with high repetition, so as to solve the problem of redundancy

difference:

  1. Different format
  2. From the perspective of memory, after the execution of the for loop, the loop variables are released with the end. However, after the execution of the while loop, because the initialization statement has been defined outside the loop structure, this variable always exists in memory. Therefore, the for loop saves memory space. (life cycle of variable)
  3. When specifying the number of cycles, the for loop is preferred, followed by the while loop; When the number of cycles is unclear, use the while loop. In the actual development, for is used the most times.
  • Another use of while loop (dead loop):
	while(true){//Dead cycle
        Loop body statement ;
        if(Conditional expression){
            break ;//When a condition is met, the break statement is used to break the loop
        }
    }
Do while loop of loop structure

Format: do while has two formats: basic format and extended format (similar to while loop)

	//Basic format
	do{
        Loop body statement ;
    }while(Conditional expression) ;
	//Extended format
	Initialization statement ;
	do{
        Loop body statement ;
        Control body statement ;
    }while(Conditional expression) ;

Execution process:

  1. Execute initialization statement
  2. Execute control body statement
  3. Judge whether the conditional expression is true
  4. If it is true, continue to execute 2 and 3 until the conditional expression is not true, and exit the loop
/*
	Requirement: output "Hello World!" 6 times on the console 
*/

class DoWhileDemo{
	public static void main(String[] args){
		
		int x = 1 ;//Initialization statement
		do{
			System.out.println("Hello World!") ;
			x++ ;
		}while(x<=6) ;
		
	}
}

Supplement: the difference between circular statements

The three loops can be converted equivalently in most cases, but there are still some small differences.

For example, do... While loops execute first and then judge, so the loop body will be executed at least once. Both for loops and while loops judge first and then execute.

Therefore, when writing programs, give priority to the for loop, followed by the while loop, and finally consider the do... While loop.

day7

Process control statements - continued 2

for loop nesting of loop structure statements

Format:

	for(Initialization statement 1;Conditional expression 1;Control body sentence 1){
		The circulatory body is for loop
		for(Initialization statement 2;Conditional expression 2;Control body sentence 2){
			Circular body sentence 2;....
		}
	}

Jump control statement

Jump control statements are divided into break statements, continue statements and return statements.

break statement

As the name suggests, it has the meaning of interruption and end. The break statement cannot be used alone.

Application scenario of break statement:

  1. In a switch statement
  2. In for loop and while loop

Function of break statement:

  1. Jump out of single layer cycle
  2. Jump out of multi-layer loop
  3. Tabbed jump out

continue Statement

The continue statement means to end this cycle and start the next cycle. The continue statement cannot be used alone.

Usage scenario of continue statement: loop

return statement

The return statement represents the returned result, which is generally not used alone. It is used at the end of the method, and the returned result should be used in combination with the methods with specific return value types in Java.

method

In Java, the method is to wrap some business code with {} code blocks to form a separate function. We call it when we need it, which realizes the reusability of the code.

Methods are divided into types with specific return value and types without specific return value.

Methods with specific return value types

Format:

	Permission modifier static modifier return value type method name(Parameter type 1 variable name 1,Parameter type 2 variable name 2......){
    	Business logic of code (operate according to requirements)
    	return result ;
	}

Permission modifiers and static modifiers: explained later in object-oriented

Return value type: data type. At present, we are studying basic data types

Method name: give a name to the {} code block, see the meaning of the name, and follow the identifier rules and "small hump naming method".

Parameter list: the parameter type is the data type, and the variable name is the name of the current form parameter. See the meaning of the name and follow the "small hump naming method".

Return result: determine the specific return result of the corresponding type according to the return value type of the method.

Call method:

  1. Output calls: calling methods directly in print statements, using hard encoding, is not recommended.
  2. Assignment call: create a new variable, then call the method and assign the return value to the new variable.
  3. Separate call: since all the calling methods have return values, separate call will not have any effect. It is not recommended.
/*
Requirements:
		Find the sum of two data (no prompt for data type, both int)
*/
class FunctionDemo{
	
	public static void main(String[] args){
		
		/*
			int a = 10 ;
			int b = 20 ;
			System.out.println(a+b) ;
			//Output call: not recommended
		*/
		//Enter or directly give the specific value: actual parameter
		int a = 10 ;
		int b = 20 ; 
		//Assignment call: Recommended
		int result = add(a,b) ;
		System.out.println("The result of the two data is:"+result) ;
	}
	public static int add(int x,int y ){//10,20: the actual parameter assigns the result to the formal parameter x,y	
		//Assignment operation
		int result = x  + y ;
		return result ;//Specific business results
	
		//return x+y ;
	}	
}

matters needing attention:

  1. Methods and methods are horizontal relations, and cannot be nested. Methods can only be called in methods.

  2. "Two unambiguous" are required when defining a method

    (1) Explicit return value type

    (2) Specify the parameter type and the number of parameters

  3. When defining methods, formal parameters must have corresponding data types

  4. When invoking a method in a method, there is no need to have data type for real parameters.

  5. The data type and sequence of actual parameters and formal parameters should correspond to each other when transferring parameters.

day8

Methods - continued

Method with no specific return value type

Format:

	Permission modifier static modifier void Method name(Formal parameter list){
        //Business logic of method
    }

Call method:

  • Output call and assignment call: since the method has no return value, neither of these calls has effect. So it only applies to individual calls.

array

The concept of array: an array is a container that can store the same data type. The elements in it must be of the same type

Array defined format

	data type[] Data name ;//The first method is recommended
	Data type data name[] ;

Precautions for definition:

An array is a reference data type. It can contain basic type data of the same type or reference type data of the same type.

Dynamic initialization of arrays

Given the length of the array, the element contents of the array are initialized by the system by default

Default initialization: the system determines the default value according to the data type stored in the array.

For example: the default value of int type is 0; The default value for double type is 0.0

Format:

	data type[] Array name = new data type[Array length] ;//The first method is recommended
	Data type array name[] = new data type[Array length] ;

For example:

	int[] arr = new int[3] ;

To the left of the equal sign:

Int: indicates that the storage elements in the current array are of int data type (basic data type)

[]: represents a one-dimensional array

Arr: the object name (variable name) representing the current array is called arr

To the right of the equal sign:

new: create an object (related to JVM memory, and the array is stored in heap memory)

Int: the object created is an array of type int

[]: indicates that a one-dimensional array is created

3: the length of the given array is 3

Output array address:

	System.out.println(arr) ;
	//The output result is "[ I@6d06d69c "

[: one dimensional array

@: address value tag

6d06d69c: hexadecimal data

Output array elements:

	System.out.println(arr[0]) ;
	System.out.println(arr[1]) ;
	System.out.println(arr[2]) ;

Note: the angle sign of the array starts from 0 and ends with the array length of - 1 (the array length is 3, so the angle sign here is 0-2)

Memory allocation in Java

Java programs need to allocate space in memory when running. In order to improve the operation efficiency, the allocated space is divided into different regions. Each divided area has a specific data processing mode and memory management mode.

  • Stack memory: store local variables

    Local variable: a variable in the method definition ({}) or on the method declaration (())

  • Heap memory: stores new things

    For example: new Scanner(System.in);

    ​ new arr[3] ;

  • Method area: store bytecode files (class es), static related things (static) and string constants (constant pool... ConstantPool). (object oriented explanation)

  • Registers: CPU related

  • Local method area: system related

Create a memory diagram of an array object

Illustration 1: define an array and output the array name and elements. Then assign values to the elements in the array and output the array name and elements again.

Illustration 2: define two arrays and output array names and elements respectively. Then assign values to the elements in the array, and output the array name and elements again.

Illustration 3: define two arrays, then define an array, assign values, and then output. When defining the third array, assign the address of the first array to the first array. Then assign a value to the third array and output the names and elements of the two arrays again.

Static initialization of array

Given the content of the element, the system assigns the length by default.

Format:

	data type[] Array name = new data type[]{Element 1,Element 2,Element 3....} ;//(recommended)
	Data type array name[] = new data type[]{Element 1,Element 2,Element 3....} ;

Simplified format:

	data type[] Array name = {Element 1,Element 2,Element 3....} ;
	Data type array name[] = {Element 1,Element 2,Element 3....} ;

Error format: when creating an array, you cannot initialize both dynamically and statically.

	data type[] Array name = new data type[]{Element 1,Element 2,Element 3....} ; Wrong!
	int[] arr = new int[3]{1,2,3} ; Wrong!

Two common exceptions in arrays:

  • Array Index Overflow

    ArrayIndexOutOfBoundsException class name

    Cause: an error is reported when accessing the index value that does not exist in the array!

    Solution: change the index value

  • Null pointer exception

    NullPointerException

    Reason for occurrence: if an object is null, an error will be reported when accessing the elements or methods in it through the current object name

    Solution: judge whether the object name is not empty

day9

Method - continued 2

Method overloading

More than one method with the same name is allowed in the same class, as long as their parameter number or parameter type are different.

Method overloading in order to improve the expansibility of a function, the method name is the same, the parameter list is different, and it has nothing to do with the return value!

The parameter list is different:

  1. Different number of parameters
  2. Different parameter types
  3. Consider the order of parameter types
//Exercise: determine which of the following methods are overloaded relationships?
public static void open(){} 
public static void open(int a){} 
static void open(int a,int b){} 
public static void open(double a,int b){} 
public static void open(int a,double b){}
public void open(int i,double d){} 
public static void OPEN(){} 
public static void open(int i,int j){}

//Answer: lines 2, 3, 4, 5 and 6 are overloaded. Lines 4 and 9 are the same, and lines 6 and 7 are the same

Arrays - continued

Array application (exercise)

1. Array traversal

/*
* Requirements: array traversal (output each element in the array in turn)
* */

class ArrayTest1 {
    public static void main(String[] args){
        int[] arr = {11,1,2,3,4,5,6,7,8,100,45,23,13,46,78,69} ;
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

2. Get the latest value from the array

/*
* Requirement: get the maximum value in the array (get the maximum value and minimum value in the array)
 * */

public class ArrayTest2 {
    public static void main(String[] args) {
        int[] arr = {69,87,52,13,24} ;
        int max = arr[0], min=arr[0];
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > max){
                max = arr[i] ;
            }else if(arr[i] < min){
                min = arr[i] ;
            }
        }
        System.out.println("The maximum value in the current array is"+max+",The minimum value is"+min) ;
    }
}

3. Array reverse order

/*
* Requirement: array elements are in reverse order (i.e. elements are swapped)
* */

public class ArrayTest3 {
    public static void main(String[] args) {
        int[] arr = {69,87,52,13,24} ;
        System.out.println("Before reverse order: ") ;
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
        System.out.println();
        System.out.println("------------------------------------");
        reserve(arr);
        System.out.println("After reverse order: ") ;
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+" ");
        }
        System.out.println();
    }
    //Mode 1
    public static void reserve(int[] arr){
        for(int start = 0 ,end = arr.length-1 ; start<end ; start++,end--){
            int temp  = arr[start] ;
            arr[start] = arr[end] ;
            arr[end] = temp ;
        }
    }
    //Mode 2
    public static void reserve2(int[] arr){
        for(int x = 0 ; x < arr.length/2 ; x++){
            int temp = arr[x] ;
            arr[x]  =arr[arr.length-1-x] ;
            arr[arr.length-1-x] = temp ;
        }
    }
}

4. Array look-up table method

/*
	Basic look-up table method of array	
	Is to get the element content through the object name [index value] of the array	 
	Data structure:
	Underlying data structure:
	Array (sequence table): fast query (direct access to corner marks), slow addition and deletion
	Linked list: composed of data field and pointer field: slow query (from the beginning of the linked list), fast addition and deletion
*/
//Guide Package
import java.util.Scanner ;
class ArrayTest4{
	
	public static void main(String[] args){
		
		//String array, static initialization
		String[] weeks = 
		{"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"} ;	
		
		//Create a keyboard entry object
		Scanner sc = new Scanner(System.in) ;
		
		//Prompt and enter data
		System.out.println("Please enter a data: ") ;
		int n = sc.nextInt() ;
		
		if(n>=0 && n<=6){
			System.out.println("You are looking for:"+weeks[n]) ;
			
		}else{
			System.out.println("Entered data,No longer within the scope of the data table...") ;
		}
	}
}

5. Array element search

/*
	Basic element query of array: in this case, the index value of the element for the first time is queried from beginning to end	
	Advanced query - binary search method - > "half thought search"
	Precondition: it can only be used when the array is ordered
*/
class ArrayTest5{
	public static void main(String[] args){
        
		int[] arr = {11,45,5,78,96,13} ; //Unordered array
		int index = getIndex(arr,45) ;
		System.out.println("The current index value of this element is:"+index) ;
		
		int index2 = getIndex(arr,450) ;
		System.out.println("The current index value of this element is:"+index2) ;
	}
    public static int getIndex(int[] array,int target){
        for(int x = 0 ; x < array.length ; x ++){
            if(array[x] == target){
                return x ; 
            }
        }
        return -1 ;
    }
}

Bubble sorting

Core idea: pairwise comparison, put the larger value of the two numbers back, so that after each comparison, the maximum value always appears at the maximum index. In this way, the array is compared in turn until the loop reaches the first array length, and the ordered array is obtained!

//Define a method, bubble sorting method
public static void bubbleSort(int[] arr){
    for(int x = 0 ; x < arr.length-1 ; x ++){//Number of comparisons
        //The elements inside are compared and exchanged
        for(int y = 0 ; y < arr.length-1-x ; y ++){//Compare elements
            //If the preceding element is larger than the following element, interchange
            if(arr[y] > arr[y+1]){
                int temp = arr[y] ;
                arr[y] = arr[y+1] ;
                arr[y+1] = temp ;
            }
        }
    }
}

Writing a blog will inevitably make some mistakes. If there is any problem with your writing, you are welcome to criticize and correct.

Topics: Java