Video address
Markdown learning
title
First level Title: # + space + title
Secondary Title: ## + space + title
...
Level 6 Title: ######## + space + title
typeface
hello world
Bold: * * hello world**
hello world
Italics: * hello world
hello world
Bold Italic: * * * hello world***
hello world
Strikethrough: ~ ~ hello world~~
quote
Choose to read ying's blog and go to the peak of life
Quote: > choose to read ying's blog and go to the peak of life
Split line
Split line:---
Split line:***
picture
! [picture name] (picture address (can be local address or Internet address))
Hyperlinks
list
Ordered list
- A
- B
- C
- D
1. + Space + content 2. + Space + content 3. + Space + content 4. + Space + content
Unordered list
- A
- B
- C
- + Space + content - + Space + content - + Space + content
form
name | Sex | Age |
---|---|---|
Zhang San | male | 19 |
name|Sex |Age --|--|-- Zhang San|male|19
Enter the source code and delete the space
Or right-click to insert the table directly
code
print("hello world")
```python print("hello world") ```
Post markdown grammar blog
Just copy the above markdown source code directly to csdn or other websites that support markdown methods
What is a computer
introduce
- Computer: electronic computer, commonly known as computer
- Modern electronic equipment that can run according to program, automatically and high-speed process massive data
- It consists of hardware and software
- Common forms: desktop computer, notebook computer, mainframe computer
- It is widely used in various fields
computer hardware
Some physical devices form an organic whole according to the system requirements, which provides a material basis for the operation of computer software
Composition of computer hardware:
- CPU
- a main board
- Memory
- Power Supply
- Main box
- Hard disk
- Graphics card
- Keyboard, mouse
- monitor
- etc.
install equipment
The simplest computer can be made up of:
- CPU
- Memory
- Motherboard
- IO device
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-15VF6Ymz-1628614588378)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210806014753463.png)]
Von Neumann architecture (father of computer)
[external chain picture transfer failed, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-IzYAeNQU-1628614588379)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210806014919598.png)]
Computer software
-
Computer software can enable the computer to complete specific functions in a predetermined order
-
Computer software is divided into system software and application software according to its function
-
systems software:
- DOS,Windows,Linux,Unix
-
Application software:
- WPS,QQ, wechat
-
Software, development, software development
-
human-computer interaction
Computer shortcuts
Alt + F4 close window
Enter OK
Num turns on the use of the keypad
CapsLock enable case
Ctrl + s save
Ctrl + c copy
Ctrl + v paste
Ctrl + z undo
Ctrl + x cut
Dos command
Open Dos command
- Command prompt under Windows system in start
- Win key + R input cmd to open the console
- Enter cmd under the path of the folder to open Dos commands in this directory
Open in administrator mode
Right click the command prompt under the Windows system in the start to open the administrator
Basic command
`D:` Switch drive letter `dir` View all files in the current directory `cd` Switch directory `cls` Clear screen `exit` Exit terminal `calc` Open calculator `mspaint`Drawing `md Directory name` create folder `rd Directory name` remove file `cd> file name` create a file `del file name` Delete file
Getting started with Java
The birth of the Java Empire
[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-vg5EzduR-1628614588380)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809071720644.png)]
[external chain picture transfer failed, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-NLbPdp3B-1628614588381)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809071949011.png)]
Java features and benefits
- Simplicity
- object-oriented
- Portability
- High performance
- Distributed
- Dynamics
- Multithreading
- Security
- Robustness
Three versions of Java
- JavaSE: Standard Edition (desktop program, console Development)
- JavaME: embedded development (mobile phones, small appliances)
- Java EE: E enterprise development (web side, server development)
JDK,JRE,JVM
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Mli4zVbi-1628614588382)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809072916498.png)]
Build Java development environment
JDK download and installation
Uninstall JDK
- Delete jdk package
- JAVA_HOME delete
- Delete the java variable in path
- java -version view whether to delete
Install JDK8
- Baidu search JDK8 and find the download address
- Login account
- Download the corresponding version of the computer
- Double click Install JDK
- Remember the installation path
- Configure environment variables
- My computer – > properties – > advanced system settings – > environment variables
- System variable – > New
- Add key as Java_ The home value is the just jdk path
- Configure the path variable and add the path value as% JAVA_HOME%\bin
- Add the path variable with the value% JAVA_HOME%\jre\bin
- Check installation
- Open cmd
- Enter java -version
[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-OTY6l6Ts-1628614588382)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809073331430.png)]
Hello World and simple syntax rules
-
Just create a new folder to store the code
-
Create a new java file
- The suffix is java
- Hello.java
-
Write hello Java file content
public class Hello{ public static void main(String[] args){ System.out.println("Hello World"); } }
-
Compile java files into bytecode
javac file name (with suffix)
[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-gcqHnskT-1628614588383)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809075414299.png)]
-
Run class file
java file name (without suffix)
[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-pMiZpNjj-1628614588384)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809075424144.png)]
Possible problems
- Case cannot be a problem. Java is case sensitive
- Try to use English
- The file name and class name must be consistent and capitalized
- Symbols need to be in English
Compiled and interpreted
-
Compiled type
Compile the program directly
Operating system (fast)
-
Interpretive type
Explain what you do
Web pages (not required to be fast)
[external chain picture transfer failed, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG toowamqj-1628614588385) (Java% E5% ad% A6% E4% B9% A0% E7% AC% 94% E8% AE% B0. Assets / image-20210809080246248. Png)]
IDEA installation
-
What is an IDE introduce
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ozc5xDNi-1628614588387)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809080605889.png)]
Install IDEA
- Go to the official website to search IDEA
- download
- [the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-NnBJSOJO-1628614588387)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809081157967.png)]
- Just go on to the next step
Simple use
-
Open the software
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-JBkp2Q8f-1628614588388)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809081936875.png)]
-
New project
[external chain picture transfer failed, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-f2tlxjm-1628614588388) (Java% E5% ad% A6% E4% B9% A0% E7% AC% 94% E8% AE% B0. Assets / image-20210809082027261. PNG)]
-
Create a Java class under src
-
Write Java code
// psvm generates public static void main(String[] args) //Some generates system out. println();
Java basic syntax
Comment, identifier, keyword
notes
We usually write code and can understand it when the amount of code is relatively small, but once the project structure becomes complex, we need to use comments
Comments are not executed. They are for those of us who write code
At ordinary times, the code must pay attention to the specification
//Is a single line comment /*For multiline comments 123*/ /** * Documentation Comments */
identifier
All components of Java need names. Class names, variable names, and method names are all called identifiers
[external chain picture transfer failed, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-C8mzB96M-1628614588389)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809084806172.png)]
keyword
[external chain picture transfer failed, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-7b0hyHJM-1628614588389)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809084602840.png)]
data type
-
Strongly typed language
- It is required that the use of variables should strictly comply with the regulations, and all variables must be defined before they can be used
-
Weakly typed language
-
Java data types fall into two categories
- Basic type
- plastic
- byte
- sort
- int
- long
- character
- char
- Boolean
- boole
- plastic
- reference type
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ln4nEHWv-1628614588389)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809085307373.png)]
- Basic type
[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG alcskumy-1628614588390) (Java% E5% ad% A6% E4% B9% A0% E7% AC% 94% E8% AE% B0. Assets / image-20210809112033282. PNG)]
expand
Integer expansion:
Base system
- decimal system
- 123456
- Octal (0)
- 010
- Hex (0x)
- 0x11
Floating point expansion:
float finite discrete rounding error is close to but not equal to
//It is best to use floating point numbers for comparison
The BigDecimal class can be used for precise comparison of mathematical tool classes
public class Demo03 { public static void main(String[] args) { float f = 0.1f; double d = 1.0/10; System.out.println(f); System.out.println(d); System.out.println(f==d); float d1 = 23232323232323f; float d2 = d1+1; System.out.println(d1==d2); } }
[external chain picture transfer failed, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-1N7e8Qnu-1628614588391)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809113245966.png)]
Character expansion
char c1 = 'a'; char c2 ='in'; System.out.println((int)c1); System.out.println((int)c2); //All characters are still numbers in nature //Encoding Unicode 2 bytes // \u0061 ==> a // \t tab // \n newline
Boolean value
boolean flag = true; if(flag){}//an old hand if(flag==true){}//Novice // Less is More! The code should be concise and easy to read
Type conversion
Because Java is a strongly typed language, type conversion is required for some operations
Cast = = = > High -- > low
Automatic conversion = = = > low -- > High
Range low----------------------------------------------->high byte, short ,char -> int -> long -> float -> double
When you cast a type, you must pay attention to the scope
int i =128; byte b =(byte)i; System.out.println(i); System.out.println(b);
[external chain picture transfer failed, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-nMvD2d40-1628614588392)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809115859216.png)]
Automatic conversion
int i =128; double b =i; System.out.println(i); System.out.println(b);
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-qqcwfkxv-1628614588392) (Java% E5% ad% A6% E4% B9% A0% E7% AC% 94% E8% AE% B0. Assets / image-202108091201568887. PNG)]
char c = 'a'; int d = c+1; System.out.println(d); System.out.println((char)d);
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-bNjZ1F9z-1628614588393)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809120717691.png)]
Note:
- Boolean values cannot be converted
- Object types cannot be converted to irrelevant types
- Force conversion when converting high capacity to low capacity
- There may be memory overflow or accuracy problems during conversion
be careful
Pay attention to overflow when operating large numbers
JDK7 new feature, numbers can be separated by underscores
int money = 10_0000_0000; int years = 20; int total = money*years;
[external link picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Qm6rvrYF-1628614588394)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809121038477.png)]
int money = 10_0000_0000; int years = 20; long total = (long)money*years; System.out.println(total);
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-kV0020Kw-1628614588394)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809121203460.png)]
Variable, constant
variable
Naming conventions All variables, methods and class names: see the meaning of the name Class member variables: initial lowercase and hump principle Local variables: initial lowercase and hump principle Constants: uppercase letters and underscores Class name: initial capitalization and hump principle Method name: initial lowercase and hump principle
Is the amount that can be changed
Java is a strongly typed language, and each variable must declare its type.
Java variable is the most basic storage unit for program summary. Its elements include variable name, variable type and scope
type varName [=value][{,varName[=value]}]; //Data type variable name = value can declare multiple variables of the same type separated by commas.
- matters needing attention:
- Each variable has a type, which can be either a basic type or a reference type
- Variable name must be a legal identifier
- Variable declaration is a complete statement, so each declaration must end with a semicolon
Variable scope
-
Class variable
Add keywords static static double salary = 2500; Subordinate class The life cycle is from the beginning of the class to the end of the class
-
Instance variable
Outside the method inside the class Instance variable:It is subordinate to the object and does not need to be initialized. Is the default value 0 for the data type.0 false
-
local variable
In the method The lifecycle must be initialized from the beginning of the method to the end of the method
constant
Constant: a value that cannot be changed after initialization! Unchanged value
The so-called constant can be understood as a special variable. Its value cannot be changed after it is set, and it is not allowed to be changed during the operation of the program.
final Constant name = value final double PI = 3.14
Constant names are usually in uppercase letters
operator
-
The Java language supports the following operators
-
Arithmetic operators: +, -, *, /,%, + +, –
-
Assignment operator:=
-
Relational operators: >, <, > =, < =, = =,! =, instanceof
-
Logical operators: & &, |, |,!
-
Bitwise operators: &, |, ^, ~, > >, <, > > >
-
Conditional operator:?:
x ? y : z
x is true and returns y
x is false and returns z
-
Extended assignment operators: + =, - =, * =/=
-
Power operation 2 ^ 3 math pow(2,3)
-
Package mechanism
-
In order to better organize classes, java provides a package mechanism to distinguish the namespace of class names
-
The syntax format of the package statement is:
package pkg1[. pkg2[. pkg3...]];
-
Red silk domain name inversion is generally used as package name
-
In order to use the members of a package, we need to explicitly import the package in the Java program. This can be done using the import statement
import package1[.package2...].(classname|*)
JavaDoc
Javadoc commands are used to generate their own API documents
-
parameter information
/* @author author @version Version number @since Indicates the earliest jdk version required @param Parameter name @return Return value @throws Exception thrown */
[external chain picture transfer failed, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-8Aidg7IU-1628614588395)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210809140659632.png)]
Generate your own API documentation
- Find tool > > generate Javadoc in the toolbar
[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ml4iAVCq-1628614588396)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/20160910175638053)]
- Then the configuration window pops up
[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-KRKwAq2A-1628614588396)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/20160910175738836)]
Parameter description
\1. Whole project > > the whole project is generated
\2. Custom scope > > the custom scope is as follows: project files, project production files, project test files, test files of the project, unknown scope, and class hierarchy
[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-xYeg6mPB-1628614588397)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/20160910180409757)]
\3. include test source contains the test directory
\4. include JDK and... Include jdk and other third-party jar s
\5. link to JDK documentation... Link to JDK api
\6. output directy is the location where the generated documents are stored
\7. Levels (classes and methods) of documents generated by private, package, protected and public
\8. Generate... On the right is the content of the selected generated document, including hierarchical tree, navigation, index
\9. On the right is the content information, author version and other information contained in the generated document
\10. Locale language type, Zh cn
\11. Other command line arguments
\12. Maximum heap
Java process control
User interaction Scanner
-
In the basic syntax we learned before, we didn't realize the interaction between programs and people, but Java provides us with a tool class that we can get user input. Java.util.Scanner is a new feature of Java 5. We can get the user's input through the scanner class
-
Basic grammar
Scanner s = new Scanner(System.in);
-
Get the input string through the next and nextLine() methods of Scanner class. Before reading, we generally need to use hasNext() and hasNextLine() to judge whether there is still input data
import java.util.Scanner; public class Demo01 { public static void main(String[] args) { //Create a scanner to receive keyboard input Scanner s = new Scanner(System.in); //Judge whether the user has entered a string if (s.hasNext()){ //Receive in next mode String str = s.next(); System.out.println("What you entered is:"+str); } s.close() } }
import java.util.Scanner; public class Demo01 { public static void main(String[] args) { //Create a scanner to receive keyboard input Scanner s = new Scanner(System.in); //Judge whether the user has entered a string if (s.hasNextLine()){ //Receive in next mode String str = s.nextLine(); System.out.println("What you entered is:"+str); } s.close(); } }
- nest()
- Be sure to read valid characters before you can end the input
- The next() method will automatically remove the whitespace encountered before entering valid characters
- Only after entering a valid character will the blank space entered after it be used as a separator or terminator
- next() cannot get a string with spaces
- nextLine()
- Take Enter as the ending character, that is, the nextLine() method returns all characters before entering carriage return
- Can get blank
It is unnecessary to judge whether there is input
Judge whether it is xxx type
Example: judging integers
import java.util.Scanner; public class Demo01 { public static void main(String[] args) { //Create a scanner to receive keyboard input Scanner scanner = new Scanner(System.in); //Receive data from keyboard int i = 0; float f =0.0f; System.out.println("Please enter an integer:"); if(scanner.hasNextInt()){ i = scanner.nextInt(); System.out.println("Integer data:" + i); }else{ System.out.println("The input is not an integer"); } System.out.println("Please enter decimal:"); if(scanner.hasNextFloat()){ f = scanner.nextFloat(); System.out.println("The decimal entered is:" + f); }else{ System.out.println("Entered is not a decimal"); } scanner.close(); } }
import java.util.Scanner; public class Demo01 { public static void main(String[] args) { //Enter multiple numbers for summation, enter numbers, press enter to confirm, and enter non numbers to end //Create a scanner to receive keyboard input Scanner scanner = new Scanner(System.in); //f is the number of received inputs, sum is the sum, and num is the number of inputs double f = 0; double sum = 0; int num = 0; while (scanner.hasNextDouble()){ f = scanner.nextDouble(); sum += f; num ++; } System.out.println("The average number entered is:"+sum/num); scanner.close(); } }
Sequential structure
-
The basic structure of Java is a sequential structure. Unless otherwise specified, it will be executed sentence by sentence.
-
Sequential structure is the simplest algorithm structure
[external chain picture transfer failed, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-vQMdFKYi-1628614588398)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210810134450117.png)]
-
Between statements and between boxes, it is carried out in the order from top to bottom. It is composed of several processing steps executed in turn. It is a basic algorithm structure that any algorithm is inseparable from.
Select structure
-
if single selection structure
-
We often have to judge whether something is feasible before we execute it. Such a process is used in the program with if
-
[external chain picture transfer failed, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ASWQYiNk-1628614588398)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210810135758440.png)]
-
grammar
if(Boolean expression){ //The statement to be executed if the Boolean expression is true. }
-
//Whether the input string is equal to hello. If so, the output of Hello does not mean nothing. //equals is required for string comparison. Try not to use it== import java.util.Scanner; public class Demo01 { public static void main(String[] args) { //Create a scanner to receive keyboard input Scanner scanner = new Scanner(System.in); System.out.println("Please enter:"); String s = scanner.nextLine(); //equals: determines whether the strings are equal if(s.equals("Hello")){ System.out.println(s); } System.out.println("End"); scanner.close(); } }
-
-
if double selection structure
-
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-av9ft7wV-1628614588398)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210810135827418.png)]
-
grammar
if(Boolean expression){ //Statement executed if Boolean expression is true }else{ //Statement executed if Boolean expression is false }
-
import java.util.Scanner; public class Demo01 { public static void main(String[] args) { //Create a scanner to receive keyboard input Scanner scanner = new Scanner(System.in); System.out.println("Please enter your grade:"); int s = scanner.nextInt(); //equals: determines whether the strings are equal if(s>=60){ System.out.println("pass"); }else{ System.out.println("Fail in grade"); } scanner.close(); } }
-
-
if multiple selection structure
-
[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Abv1EDvG-1628614588398)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210810140137315.png)]
-
grammar
if(Boolean expression 1){ //Boolean expression 1 sets up the code to execute }else if(Boolean expression 2){ //Boolean expression 2 sets up the code to execute }else if(Boolean expression 3){ //Boolean expression 3 sets up the code to execute }else{ //Boolean expressions are not valid for executing code }
-
import java.util.Scanner; public class Demo01 { public static void main(String[] args) { //Create a scanner to receive keyboard input Scanner scanner = new Scanner(System.in); System.out.println("Please enter your grade:"); int s = scanner.nextInt(); //equals: determines whether the strings are equal if(s==100){ System.out.println("Congratulations, full marks"); }else if(s>=80 && s<100){ System.out.println("Excellent results"); }else if(s>=60 && s<80){ System.out.println("Good results"); }else if(s>=0&&s<60){ System.out.println("fail,"); }else{ System.out.println("The grade entered is incorrect"); } scanner.close(); } }
-
-
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. Else if... Else can be nested like an IF statement
-
grammar
if(Boolean expression 1){ //If Boolean expression 1 holds, execute the statement if(Boolean expression 2){ //If Boolean expression 2 holds, execute the statement } }
-
-
switch multiple selection structure
-
switch intelligence matches an exact value, not a range
-
Another way to implement the multi selection structure is the switch case statement
-
The switch case statement determines whether a variable is equal to a value in a series of values. Each value is called a branch
-
The variable types 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
-
grammar
switch(expression){ case value: //sentence break; case value: //sentence break; default: //sentence }
-
Cyclic structure
-
while loop
-
As long as the Boolean expression is true, it is always executed
-
In most cases, we stop the loop. We need to end the loop by invalidating the expression
-
In a few cases, it needs to be looped all the time, such as the monitoring of the server
-
If the loop is always true, it will cause wireless loop [dead loop]. We should try our best to avoid dead loop in normal business programming, which will affect the performance of the program or cause the program to get stuck and crash
while(Boolean expression){ //Code executed in a loop }
import java.util.Scanner; public class Demo01 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int i = scanner.nextInt(); int sum = 0; while (sum<=i){ System.out.println(sum); sum++; } scanner.close(); } }
-
-
do... while loop
- Execute before Judge
- It's the same as a while loop, but execute the code at least once
-
for loop
-
Although all loop structures can be represented by while or do... While, Java provides another statement - for loop, which makes some loop structures simpler
-
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. The syntax is as follows
for(initialization;Boolean expression;to update){ //Code statement }
-
Find odd and even numbers within 100
public class Demo01 { public static void main(String[] args) { int jishu=0; int oushu=0; for(int i=1;i<=100;i++){ if(i%2==0){ oushu += i; }else{ jishu += i; } } System.out.println("Odd number is" + jishu); System.out.println("Even number is" + oushu); } }
-
Find 99 multiplication table
public class Demo01 { public static void main(String[] args) { for(int i=1;i<=9;i++){ for(int j=1;j<=i;j++){ System.out.print(i+"*" + j +"="+i*j+" "); } System.out.println(); } } }
-
-
An enhanced for loop is introduced in Java 5, which is mainly used for arrays
-
grammar
for(Declaration statement : expression){ //Executed code }
-
example
int[] num = {10,20,30,40,50}; for(int x:num){ System.out.println(x); }
-
break&continue
-
Break in the body 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)
-
In the body of a loop statement, continue statement is used to terminate a loop process, that is, skip the statement that has not been executed in the loop, and then determine whether to execute the loop next time
-
goto keyword
-
goto is prone to problems
-
The goto keyword has long appeared in programming languages. Although goto is still a reserved word in Java, it is not officially used in the language. There is no goto in Java. However, we can see some shadows of goto in the two keywords break and continue - labeled break and continue
-
"label" refers to the identifier followed by a colon, for example: label:
-
For Java, the only place where the label is used is before the loop statement. Second, the only reason for setting the label before the loop is that we want to nest another loop in it. Because the break and continue keywords usually only end the current loop and are weakly used with the label, they can end to the place where the label exists
-
practice
-
Print triangles
-
public class Demo01 { public static void main(String[] args) { for (int i = 0; i < 5; i++) { for (int j = 5; j >= i; j--) { System.out.print(" "); } for (int j = 1; j <= 2*i+1; j++) { System.out.print("*"); } System.out.println(); } } }
-
Java Procedure
-
System.out.println(), what is it
-
A Java method is a collection of statements that together perform a function
- Method is an ordered combination of steps to solve a class of problems
- Method is contained in a class or object
- Methods are created in the program and referenced elsewhere
-
Principle of design method: the original intention of method is function block, which is the collection of statement blocks to realize a certain function. When designing methods, we'd better keep the atomicity of methods, that is, a method can only complete one function, which is conducive to our later expansion.
-
Addition method
-
public class Demo01 { public static int add(int a,int b){ return a+b; } public static void main(String[] args) { int a = 1; int b = 5; int sum = add(1,2); System.out.println(sum); } }
-
-
Java methods are similar to functions in other languages. They are a piece of code used to complete specific functions. Generally, defining a method includes the following syntax:
- The method contains a method header and a method body. The following are all parts of a method:
- Modifier: modifier, which is optional and tells the compiler how to call the method. Defines the access type of the method
- Return value type: the method may return a value. returnValueType is the data type of the return value of the method. Some methods perform the required operation but do not return a value. In this case, returnValueType is the keyword void.
- Method name: is the actual name of the method. The method name and parameter table together constitute the method signature.
- Parameter type: the parameter is like a placeholder. When a method is called, it is passed to a parameter, which is called an argument or variable. Parameter list refers to the parameter type, order and number of parameters of the method. Parameters are optional, and methods can contain no parameters.
- Formal parameter: used to receive external input data when the method is called
- Argument: the data actually passed to the method when the method is called
- Method body: the method contains specific statements that define the function of changing the method
- The method contains a method header and a method body. The following are all parts of a method:
-
Syntax:
Modifier return value type method name(Parameter type parameter name){ ... Method body; ... return Return value; }
-
Method call:
-
Calling method: object name Method name (argument list)
-
Java supports two methods of calling methods, which are selected according to whether the method returns a value
-
When a method returns a value, the method call is usually treated as a value. For example:
int larger = max(30,40)
-
The return value of the method is void, and the method call must be a statement.
System.out.println("Hello World")
-
Method overloading
We can set multiple methods with duplicate names, but we should ensure that the parameters of each method are different.
- Overloading is a function with the same function name but different formal parameters in a class
- Rules for overloading methods
- Method names must be the same
- The parameter list must be different (different number, different types, different order of parameters, etc.)
- The return types of methods can be the same or different
- Just different return types are not enough to overload methods
- Realization theory
- If the method names are the same, the compiler will compare the matching one by one according to the number of parameters and parameter types of the calling method to select the corresponding method. If the matching fails, the compiler will report an error
Command line parameters
Sometimes you want to pass a message to a program when it runs. This is achieved by passing command line arguments to the main() function
-
example
public class Demo01 { public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.println("args[" + i +"]:" + args[i]); } } }
It should be noted here that you cannot run under this file path, otherwise you will not find the main class. You need to run under the full path file address in the first path of idea before you can run
Variable parameters
- There may be uncertain transmission parameters. We can use the main method to pass a variable parameter.
- JDK1. Starting from 5, Java supports passing variable parameters of the same type to a method.
- In the method declaration, add an ellipsis (...) after specifying the parameter type
- Only one variable parameter can be specified in a method. It must be the last parameter of the method, and any ordinary parameter must be declared before it
public class Demo01 { public void test(int... i){ for (int j:i) { System.out.println(j); } } public static void main(String[] args) { Demo01 demo01 = new Demo01(); demo01.test(1,2); } }
recursion
-
Method A calls method B, which is easy for us to understand
-
Recursion is calling itself
-
Using recursion, we can solve some complex problems with simple programs. It usually transforms a large problem layer by layer into a smaller problem similar to the original problem. The recursive strategy only needs a small number of programs to describe the multiple repeated calculations required in the problem-solving process, which greatly reduces the amount of code of the program. The ability of recursion is to define an infinite set of objects with limited statements
-
The recursive structure is divided into two parts
- Recursive header: when not to call its own method. If there is no head, it will fall into a dead cycle
- Recursive body: when do I need to call my own method
-
//Factorization of input number import java.util.Scanner; public class Demo01 { public static int f(int n){ if (n==1){ return 1; }else{ return n*f(n-1); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int num = scanner.nextInt(); System.out.println(f(num)); } }
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-fGyYHyX7-1628614588399)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210810232142426.png)]
-
Pre stage
-
boundary condition
-
Return phase
array
Array overview
- An array is an ordered collection of data of the same type
- Array describes several data of the same type, which are arranged and combined in a certain order
- Among them, each data takes an array element, and each array element can access them through a subscript
Array declaration creation
-
Array variables must be declared before they can be used in the program. The following is the method of declaring array variables:
dataTyye[] arrayRefVar //Preferred method int[] nums; dataType arrayRefvar[] //The effect is the same, but it is not the preferred method int nums[];
-
The Java language uses the new operator to create arrays. The syntax is as follows:
dataType[] arrayRefVar = new dataType[arraySize]; int[] nums = new int[5]
-
The elements of the array are accessed through the index. The array index starts from 0
-
Get array length
arrays.length nums.length
public class Demo01 { public static void main(String[] args) { int[] nums; //Declaration array nums = new int[5]; //Create an array to open up space, where you can store 5 int type data nums[0] = 1; nums[1] = 2; nums[2] = 3; nums[3] = 4; nums[4] = 5; } }
-
Array initialization
-
initiate static
int[] a = {1,2,3}; Man[] mans = {new Man(1,1),new Man(2,2)}
-
dynamic initialization
int[] a = new int[2]; a[0] = 1; a[1] = 2;
-
Default initialization of arrays
//Array is a reference type. Its elements are equivalent to the instance variables of the class. Therefore, once the array is allocated space, each element is implicitly initialized in the same way as the instance variables
-
Memory analysis
[external chain picture transfer failed, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-jBDwokYY-1628614588399)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210810234855168.png)]
[the external chain picture transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-KPpzq3YT-1628614588401)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210810235139503.png)]
Characteristics of array
- The length is determined. Once an array is created, its size cannot be changed
- Its elements must be of the same type, and mixed types are not allowed
- The elements in the array can be any element type, including its basic type and reference type
- Array variables belong to the reference type, and arrays can also be regarded as objects. Each element in the array is equivalent to the member variables of the object. The array itself is an object. In Java, the object is in the heap. Therefore, whether the array saves the original type or other object types, the array object itself is in the heap.
- If the legal range [0,length-1] of the subscript exceeds the boundary, an error will be reported
Array usage
-
For each loop
//For each traversal array public class Demo01 { public static void main(String[] args) { //No subscript int[] nums = {1,2,3,4,5}; for (int i: nums) { System.out.println(i); } } }
-
Array as method parameter
//Reverse string public class Demo01 { public static void main(String[] args) { int[] nums = {1,2,3,4,5}; int[] result = reverse(nums); for (int i = 0; i < result.length; i++) { System.out.println(result[i]); } } public static int[] reverse(int[] arrays){ int[] result = new int[arrays.length]; for (int i = 0,j = arrays.length-1; i < arrays.length; i++,j--) { result[j] = arrays[i]; } return result; } }
Multidimensional array
-
Multidimensional arrays can be regarded as arrays. For example, a binary array is a special one bit array, and each element is a one-dimensional array.
-
Two dimensional array
int a[][] = new int[2][5]
-
Analysis: the above two-dimensional array a can be regarded as an array with two rows and five columns
[external chain picture transfer failed, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-8FOX1KtW-1628614588401)(Java%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0.assets/image-20210811001558381.png)]
public class Demo01 { public static void main(String[] args) { int[][] a = {{1,2},{3,4},{5,6},{7,8}}; } }
Arrays class
-
Array tool class java util. Arrays
-
There are no methods for array objects, but the API provides a tool class Arrays for us to use, so we can perform some basic operations on data objects.
-
View JDK help documentation
-
All the methods in the Arrays class are static methods decorated with static. When using them, you can call them directly with the class name. Second, you don't need to call them with objects (Note: it's "don't use" instead of "can't")
-
It has the following functions
-
Assign value to array: through fill method
-
Sort the array: sort in ascending order through the sort method
-
Compare arrays: use the equals method to compare whether the element values in the array are equal
-
Find array elements: binary search can be performed on the sorted array through the binarySearch method
public class Demo01 { public static void main(String[] args) { int[] a={5,3,1,4,2}; System.out.println(a); //[I@1b6d3586 System.out.println(Arrays.toString(a)); //[5, 3, 1, 4, 2] Arrays.sort(a); System.out.println(Arrays.toString(a)); //[1, 2, 3, 4, 5] } }
-
Bubble sorting
import java.util.Arrays; public class Demo01 { public static void main(String[] args) { int[] a = {5,1,3,7,4}; int[] b = buSort(a); System.out.println(Arrays.toString(b)); } public static int[] buSort(int[] arrays){ for (int i = 0; i < arrays.length-1; i++) { for (int j = 0; j < arrays.length-i-1; j++) { if(arrays[j]<arrays[j+1]){ int a = arrays[j]; arrays[j] = arrays[j+1]; arrays[j+1] = a; } } } return arrays; } }
Sparse array
-
Gobang has the operations of saving, exiting and continuing to play
I think a lot of zeros are stored, so I record a lot of meaningless data
-
Solution: sparse array
-
When most elements in an array are 0 or an array with the same value, you can use a sparse array to save the array.
-
Sparse arrays are handled as follows:
- A record array has several rows and columns, and how many different values
- Record the elements, rows, columns and values with non-stop values in a small-scale array, so as to reduce the size of the program
-
As shown in the following figure: the original array is on the left and the sparse array is on the right
[external chain picture transfer failed, the source station may have anti-theft chain mechanism, so it is recommended to save the picture and upload it directly (IMG iolcwhuk-1628614588401) (Java% E5% ad% A6% E4% B9% A0% E7% AC% 94% E8% AE% B0. Assets / image-20210811003833824. Png)]
import java.util.Arrays; public class Demo01 { public static void main(String[] args) { int[][] array1 = new int[11][11]; array1[1][2] = 1 ; array1[2][3] = 2 ; for(int[] anInt:array1){ for(int i:anInt){ System.out.print(i+" "); } System.out.println(); } int[][] result = xiShu(array1); for (int i = 0; i < result.length; i++) { System.out.println(Arrays.toString(result[i])); } } //Convert 2D array to sparse array public static int[][] xiShu(int[][] arrays){ int sum = 0; for (int i = 0; i < 11; i++) { for (int j = 0; j < 11; j++) { if(arrays[i][j] != 0){ sum++; } } } int[][] result = new int[sum+1][3]; result[0][0]= 11; result[0][1]= 11; result[0][2]= sum; int resnum = 1; for (int i = 0; i < 11; i++) { for (int j = 0; j < 11; j++) { if(arrays[i][j] != 0){ result[resnum][0] = i; result[resnum][1] = j; result[resnum][2] = arrays[i][j]; resnum++; } } } return result; } }