week02_ Handwritten notes

Day_1

I java program - flow control statement

1. Sequential structure statement

After entering the main program main Method by jvm After call
 The code is executed from top to bottom System class:Late learning
 						function:System.exit(0);//0 this parameter terminates the jvm normally
 						

2. Select structure statement

2.1 if structure statement
Format 1:if(expression){
		sentence;
	   }
	   
Execution process:1)First judge whether the expression is valid
		2)If established,Execution statement content
		3)Not established,Do not execute
 matters needing attention:1):if Following expression{} :Left brace{You can't have semicolons where you want to,Braces are not allowed where semicolons exist
			Local code block{}	:Define the life cycle of a variable
 Format 2:  if(expression){
			sentence;
}else{
		Statement 2
}
	   			
demand:Simulate the execution process of user login
1)Assume that the user name and password already exist(Simulation database)
		String username = "admin";
		String password = "admin";
2)Enter the user name and password with the keyboard
		uname
		psw
3)judge
		If entered name and pwd Consistent with in the database,Then prompt"Congratulations,Login succeeded"
		atypism,Then prompt"Login failed"

Scanner Class
	public String nextline():Input String Type data
1)The user name and password are known to exist-------String type(String type)
		String Username = "admin";
		String Password = "admin";    That is, create and prompt for string entry
			Scanner Variable name = String nextLine();
	   2)Create keyboard entry object
	  System.out.println("Please enter your user name");
	  System name = sc.nextline();
	  System.out.println("Please enter your password");
	  System password = sc.nextline();
	   3)judge 
	   If consistent,Entered Username , name and Password,Prompt successful login
	   otherwise,Tips"Wrong user name or password"
	   if(name.equals(name)&&)(password.eqaals(psw)){
	   		System.out.println("Congratulations,Login successful");
	   }else{
	   		System.out.println("Wrong user name or password");
	   
	   }
	   
       4)output
   			 System.out.println("over");
    	
analysis:

1)No learning database,Intelligent simulation;Provide a user name and password username,password;
2)Keyboard input data: String String data(String comparison is a reference data type,out-of-service==)
						user name
						password

3)conduct if judge
	if(Enter a user name and password that matches a known user name and password) Login succeeded,Otherwise, an error message will be prompted  
    
	if Nested use of format 2----------->if Multiple use of format

Format 3:  if(Judgment statement){
			System.out.println("Output statement");			
		}else if(Judgment relation II){
			Statement 2
		}else if{
			Statement 3
		} ........
	Be careful when judging:Standardization of data
					1)Data within the detection range
					2)Data outside the detection range
					3)Detect critical data

Simulated user login in format 2
import java.util.Scanner;//Guide Package
    	class DengLu{
    	public static void main(String[] args){
			String name = "admin";
			String pwd = "admin"; //Suppose the name and password already exist
			
			Scanner sc = new Scanner(System.in);//Create keyboard scanner entry object
			
			System.out.println("Please enter your user name");
			
			String username = sc.nextLine(); //Accept variable names with line() and nextstring()
			System.out.println("Please enter your password");
			String password = sc.nextLine();//Accept variable names using String type and nextLine()
				if(username.equals(name)&&passawrod.equals(psw)){	//Fixed format: enter the variable name Equals (string)
				//Judge whether the input user name is consistent with the user name in the existing database. You cannot use = =, = = is the reference data type, and the output result is true / false, not the string content
					System.out.println("Congratulations,Login successful");
				}else{
					System.out.println("Wrong user name or password");
				}
			System.out.println("over");
			
		}
    	}

2.1.1 difference between if format 2 and ternary format
if Statement format 2:The range is larger than that of ternary operators;
			Process control statements can operate on both output statements and specific data values
			Ternary operators can only operate on specific data
 summary:Can be implemented using ternary operators,Must be able to use If Format 2 o realization
	conversely if Format 2 can be implemented,Ternary may not be realized
2.1.2 nested use of if structure format 2
if(expression){
	if(Expression 1){
		Statement 1
	}else{
		Statement 2
	}
}else{
	if(Expression 3){
		Statement 3
	}else{
		Statement 4
	}
}
Execution process:1)First judge whether the expression is valid,Hold judgment expression 1 again.Expression 1: execute statement 1,Expression 1 does not hold. Execute statement 2
			
		2)Execute if the expression does not hold else,Judge expression 3 again,If true, execute statement 3;Execute statement 4 is not established
2.2 switch structure statement - matching statement
format:		switch(switch)(expression){
			case Value 1:	//The value of case must be a constant
				Statement 1;	//System.out.println("Monday");
				break(break);
				......
				......
				......
				default:(chinese:default)
					Statement 3
				break;
				
}
Execution process:
1)Determine the value and of the expression case Match with value 1,If the match is successful,Execute statement 1,break end
2)If case Value 1 does not match,Continue and case Compare with the value of 2,If match,Execute statement 2;
      ..........
3)If the above case All values are equal to switch The result of the expression in does not match,Then it will be executed in the end default Statements in,Then the program executes to the end by default,break end;

Interview questions:switch Middle expression,What data types can it be?
Basic data types that can be used:
					byte,short,char,int
					jdk5 in the future,Can follow enumeration(enum);
					jdk7 in the future,Can be String type;

case Penetration of:utilize case Code optimization through penetration
2.2.1 precautions in switch statement
1)case Statement can only be followed by a constant;
2)case In a statement break You must bring it,Otherwise, it will cause a phenomenon:case pierce through
		Because of a case Already matched,If not at this time break,So keep going down case Penetration in statement,Know encounter case There are break,Then stop penetration;
3)switch What is the end condition of the statement?
	a)sentence break end
	b)The program executes to the end by default
4)default Can be anywhere in the program,It can be omitted at the end of the program break,In its		He must take his seat with him break,Otherwise, it will cause case pierce through;
5)default Service conditions of:Entered values and case When they don't match,implement default

3. Circular structure statement

3.1 for loop structure statement
format:		for(Initialization statement;Conditional expression;Control body statement(Step size statement)){
			Loop body statement;
			output
}

Execution process:	1)Initialization statement for assignment,Execute only once
		2)Then judge whether the conditional expression is true
			If established,Execute loop body statement-----Then execute the control body statement
		3)Continue to judge whether the conditional expression is true
			If established,Continue executing the loop body statement
					........
		4)Execute to condition expression not valid,End of loop body statement
	//Find the sum of 1-10
	int sum = 0;
	 for(int x = 0;x<=10;x++){
	       sum += x ; 
	 }
	 System.out.println("The value of the sum is:+sum);
	 
	
3.1.1 summation idea of for loop
Two variables
1)Final result variable int sum = 0;
2)Cyclic variable x In constant change
3)Loop to get changing data x
4)Output final result variable X that will do
 demand:1-100 Sum
class Qiuhe{
	public static void main(String[] args){
		int sum = 0 ;		//Addend ---- final result variable
		for(int x = 1;x<=100;x++){		//Int x = 1 start addend
			sum += x;
		}
		System.out.println("0~100 The sum of the values is:"+sum);
	}
}
3.1.3 number of daffodils
definition:It refers to three digits,And the cube sum of each bit is the current data itself
		eg: 153---3*3*3*+5*5*5*+1*1*1
 demand:Find the number of all daffodils
 analysis:1)Value range: 100-999
2)Determines the value on each of the three digits
 law:			int ge = x % 10;
				int shi = x / 10 % 10 ;
				int bai = x / 100 % 10;      perhaps x / 100 ; 
3)As long as the conditions are met		x = ge*ge*ge+shi*shi*shi+bai*bai*bai;
4)output

		class Shuixianhua{
	public static void main(String[] args){
		System.out.println("What is the number of all daffodils:");
		for(int x = 100 ; x <= 999 ; x++){
				int ge = x % 10;
				int shi = x / 10 % 10 ;
				int bai = x / 100 % 10; 
			if(x == ge*ge*ge+shi*shi*shi+bai*bai*bai){
				System.out.println(x);
			}
		}
		
	}
}
3.1.3 statistical thinking
demand:Count how many daffodils there are?
	step:
		1)Defining statistical variables count,Start from 0
		2)Narcissistic number :Three digit,Clear scope 100-999 between x
		3)Identify each data itself
		4)After meeting the conditions count++
		if(Relational formula){
			Control body statement
			count++;   //Statistical variables++
		}
			
		5)Just output statistical variables connt;
3.1.1 nesting of fou loops (understanding)
for(Initialization statement;Conditional expression;Control body statement){
		Circular body sentence 1 is for loop
		for(Initialization statement 2;Conditional expression 2;Control body sentence 2)
				...Circular body sentence 2
}

java Escape characters in   \t------Tab(Must be\)

Exhaustive method:Limit value method------Suppose a value reaches the maximum,You can determine his scope.   Typical interview questions:Chicken and rabbit in the same cage,Brick moving
3.2 while loop structure statement
Extended format: 

Initialization statement;
while(Conditional expression){
	Loop body statement;
	Control body statement;
}
			
3.2.1 difference between while loop and for loop
common ground:Can describe the idea of circulation,Optimize highly repetitive code,Solve redundancy problems
 difference:  1)Different format
		2)From the perspective of memory,for After recycling,Then the current variable is released,and while You can access this variable,So relatively speaking,for Cycling saves more storage space;
		3)Specify the number of cycles,Preferred use for loop,Again while loop
			while loop:Unclear number of cycles to use
			
			In actual development,for Most recycled
			while The cycle is generally based on while(ture){}Use in dead cycle//When a certain condition is reached, break is interrupted
				
	
3.3 do while cycle
format:
1)Initialization statement;
	do{
		Loop body statement;
		Control body statement;
	}while(Conditional expression);
	
Execution process:
		1)Initialization statement execution
		2)Execute conditional expression,If the conditional expression does not hold,The loop body is executed at least once
		3)If the conditional expression holds......Then control statement,Judge by this.
		
do-while The biggest difference between the loop and the other two loops is:The circulating body circulates at least once;
		do{
			System.out.println("I like Gao Yuanyuan,Although she is 42 years old") ;
			x ++ ;
		}while(x<=6) ;
3.4 dead loop of while and for
jdk Provides a mathematical operation class java.lang.Math(Is a data tool class)
For trigonometric functions,logarithm,Index and so on
	Math Class provides a method:
			public static double random():Generate a random number[0.0,1.0)   //This is a class
			double result = Math.random();Randomly generate a value   
	int result = (int)(Math.random()*100+1)   //Cast to int type 1-100
	
Word guessing game
 Implementation steps:
1)Guess 1-100 Random number between,First, we have to generate 1-100 Random number of
		int Variable name = (int)(Math.random()*100+1);
		//Continuously enter data, and use the following logic ----- use while(ture) {}
2)Enter a data with the keyboard int-----guessNum
3)judge: use guessNum And generated 1-100 Compare random numbers between;
		If it's big,Tips"I'm sorry,Your guess is too big"
		If it's small,Tips"I'm sorry.Your guess is small"
		If consistent,Tips"Congratulations,You guessed right"
	import java.util.Scanner;
	class WhileTest{
		public static void main(String[] args){
		System.out.println("Ready to play the game....");\
		int num = (int)(Math.random()*100+1);
		int count = 0;
		while(true){
		Scanner sc = new Scanner(System.in);
		count ++;
		System.out.println("Please enter the data you guessed");
		int guessNum = sc.nextInt();
		if(guessNum>num){
			System.out.println("I'm sorry,Your guess is too big")
		}else if(quessNum < num){
			System.out.println("I'm sorry,Your guess is small")
		}else{
			System.out.println("Congratulations on your second visit"+count+"You guessed right")
			break;
		}
		}
		System.out.println("game over,looking forward to your next visit");
		
        }
	}
	
format:for Loop format
	for(;;){
		Output statement 1
	}
	while Loop format:
	while(ture){
		Output statement 2
	}

II Jump control statement (key)

Jump control statement:break: Interrupt 1)Cannot be used alone 2)Can only be used in two scenarios switch And in circulation
		   continue;Generally used in circular statements
		   			1)Indicates to stop the current cycle,Immediately enter the next cycle
		   return(It has something to do with the method):Returns a result,Normally,Not alone,combination java Methods with specific return value types in,Used alone at the end of the method

III. what is a function (emphasis)

IV What is the method of introduction

In java, the method is to wrap some businesses with {} code blocks and name them as "method name", "method name" needs to see the name and meaning, and use "small hump naming method";

In the future, we can call our own method directly in the main method.

V About method use and call with return value type

5.1 use of methods with return value types
Fixed writing method of return value type:
	Permission modifier return value type method name(Parameter type 1 variable 1,Parameter type 2 variable 2.......){
					code
					return result
	}
explicate:
	Permission modifier:Now fixed use public,Access permissions are large enough,You must bring it static;public static
	return type:Is the data type----Basic data types are studied
	Method name:to{}give a name,See the name and know the meaning,Using the small hump nomenclature
	parameter list:
		Parameter type------data type,Now use the basic data type
		Variable name:--------Name the current form parameter,See the name and know the meaning,Using the small hump nomenclature
	return result:Used in conjunction with methods with return value types
			What is the return value type,I'll return you the specific results
5.2 method call with return value type
Output call:Not recommended,The output type has a direct return value,Harden code,Can no longer be used
 Assignment call:proposal: There will be methods that return value types result Result assigned to main Method variables,result Can continue to use
 Individual call:stay main Call in method,But there is no output statement(There are results,But no output)
5.3 execution flow of method call with return value type
1)Actual parameters----Later, you can enter data with the keyboard
2)Find out if there are child methods in the class
3)At the same time, the actual parameters ab Assign to formal parameter xy
4)_Business logic:Is to sum the values
5)Return results
5.4 application scenarios for methods with return value types
For now,Is to give you a need,Use method to complete,Output the results to the console for display
 Later,Front and rear end interaction
5.5 considerations for defining methods with return value types
1)Methods and methods are horizontal relations,Cannot nest;
2)When defining a method, you need two explicit methods
	1.Explicit return value type
	2.Specify the return type and number of parameters
3)When defining methods,Formal parameter must carry data type
4)In actual parameters main in,When calling a method,
type
5)Actual parameters and formal parameters,Parameter transmission time,Data types should correspond one by one;

Vi Method with no return value type

6.1 use of methods without return value type
Code block for a function{},There is no specific return value type,According to the grammar,Must have a value,Java A keyword is provided:Instead, there is no specific return value type void
 format:Permission modifier return value type method name(Formal parameter list){}
	public static void Method name(Formal parameter list){}
Content in method:Direct output or other operations;unwanted return operation;
6.2 precautions for methods without return value type
Two clear:
1)Explicit return value type;There is no specific return value type,use void replace
2)Specify the parameter type and the number of parameters:------If not, you can directly take the specified parameters in the method

6.3 call of method without return value type
Output call:Can't use
 Assignment call:Can't use
 Individual call: Can only be called individually	Method name(parameter list);

7. Array - default one-dimensional array

7.1 what is an array?
definition:Only containers of the same data type can be stored;(Can only contain data of one data type)
format: 1)data type[] Array name(recommend);		int[] arr;  Defines a int Array of type,arr variable
	 2)Data type array name[];			int arr[];Defined int Type arr array
	 
	 The array itself is a reference data type,The element content stored in it can be a basic type element of the same type or a reference type of the same type.
	 Arrays also belong to the range of variables;
	Disadvantages of array:Fixed length,Cannot be unchanged
7.2 array initialization
There are two ways to initialize:1)dynamic initialization
				2)initiate static
 dynamic initialization:We give the length of the array.The element contents of the array are initialized by default
		format: data type[] Array name = new data type[Array length];
		such as: int[] arr = new int[3] ; 
			explain:int :  Storage type is int type
				[]	:   Represents a one-dimensional array
				arr :	The object name of the current array(Variable name)
				new :	create object
				int	:The object created is a int Array of type
				[]	:	Indicates that a one-dimensional array is created
				3	:	The length of the array we give is 3
 Get element format:		By array name[Index value(Angle scale value)]
					Index value starts at 0

initiate static		Format data type[] Array name = {Element value}; 	eg: int[] arr = {1,2,3,4.....}
7.3 jvm memory allocation
Stack memory:1)local variable:Variable characteristics in the method definition or on the method declaration:fifo

Heap memory:new Everything that comes out is in heap memory eg:new Scanner(System.in); new arr[3];
Method area:class:Bytecode file area
			2)static region--Later things about static
 register:and cpu of
 Local method area:System related
		
7.4 two common exceptions of array
An exception occurred in the program.An exception is a class,Learn something in common classes in the future
1)Array subscript out of bounds exception( ArrayIndexOutOfBoundsException)---An exception occurred while the program was running
		Solution---Change index value
2)In actual development,Null pointer exceptions often occur(NullPointerException)--Is when we access an object,The object is null
		Non null judgment	 if(sc!=null){
				Business logic
		}else{
		System.out.println("Data error") ;
		}
	
7.5 application of array
1)Traversal array:Is to display the element values of the array one by one
						method:There is an attribute in the array length,Can quickly get the array length
                        Length of format array=Array name.length
                   for(int x=1 ; x<array.length ; x++){
                   			System.out.ptintln(array[x]) ;
                   }
2)Method overloading(overload):When the functions of methods are the same,We can define methods with the same name,The parameter list is different,It can improve the scalability of functions
			summary:Same method name,The parameter list is different,Independent of return value
	The parameter list is different:Different number of parameters
				Different parameter types
				The order of parameter types is considered
3)Method rewrite(override)
4)Array assignment:Assign the first array object to the third array,Array 1 and array 3 share the same object,Can access the element value through the heap memory of the object;

										
7.6 other applications of arrays
1. When traversing an array:Elegant format traversal
2.Maximum value problem of array
		1)Assume a reference as the maximum value	arr[x]=max ;
		2)Then traverse the array,Compare all elements to the maximum,If it is larger than the reference,Reassign to max
		3)Final output max
		arr[0] = max ;
for(int x=1 ; x<array.length ; x++){
	if(array[x]>max){
	array[x] = max ;
	}
}
System.out.println("max");
3.Reverse order of array
	Is to swap the first element and the last element in the array,Swap the second element with the penultimate element,and so on
 Mode 1:for(int x=0 ; x/2=0; x++){
	int temp = arr[x] ; 
	arr[x] = arr[arr.length-1-x] ;
	arr[length-1-x] = temp ;
	}
Mode II:
for(int start=0 , int end=arr.length-1;start<end;start++,eng--){
int temp = arr[start]  ;
arr[start] = arr[end] ; 
arr[end] = temp ; 
}
4.Basic look-up table method of array----String type requires string type string
 Is the object name through the array[Index value]---Get element content
 String array: string[] weeks = {"Monday","Tuesday","Wednesday"....}
5.Basic element search method of array:The index value of the element in the query array	
Look up the index value of the first occurrence of the element,Every query from beginning to end,This array can be unordered,It can also be orderly!
Mode 1:Return value type parameter = Method name(Actual parameter list,Element value) ;
public static int getnum(int [] array,int target)
 for(int x=0 ; x<arr.length ; x++){
   if(array[x] == target){
   return x	;
   }else{
   return -1 ;
   }  
 }
Mode II(recommend);Hypothetical thought
public static int getnum(int [] array,int target)
int index = -1
 for(int x=0 ; x<arr.length ; x++){
 if(array[x] == target){
 		index = x ;
 		break ;
 }
 return index ; 
 }

7.7 advanced sorting of arrays - < bubbling
Sorting method----Bubbling:A relatively stable sorting method
 thought:Pairwise comparison,Put the larger value back,The first comparison is over,The maximum value appears at the maximum index:Then compare them in this way,You can get an ordered array!
law:1)Pairwise comparison,Put the larger value back,The first comparison is over,The maximum value appears at the maximum index
2)First comparison,There are 0 no more than
	Second comparison,One is not better than
		,,,,,,
	Number of comparisons: arr.length -1 second
	
for(int x=0 ; x<array,length-1 ;x++){
	for(int y=0;y<array,length-1-x ; y++){
		if(array[x+1]<array[x]){
		int temp = array[x];
		array[x] = array[x+1] ;
		array[x+1] = temp ;
		}
	}
}

Keywords: Java Back-end

Added by phpvn.org on Mon, 03 Jan 2022 12:40:41 +0200