1, Computer overview
1.1 computer components
Computers are mainly divided into two categories: hardware and software
Hardware: it is composed of many modular components with different functions, and completes the four operation steps of input, processing, storage and output with the cooperation of software, mainly some electronic components.
Software: a series of computer data and instructions organized in a specific order. It is a non tangible part of the computer.
Common hardware:
- Arithmetic unit: the operation system of the computer, which is responsible for the operation of data; Equivalent to the brain of a computer.
- Controller: a computer control system that coordinates and controls the work between components.
- Controller + arithmetic unit = central processing unit (CPU)
- Memory: computer storage system, which is divided into internal memory (ROM, the storage device for temporarily storing data, and the data disappears after power failure) and external memory (RAM, the permanent storage device). The storage forms are stored in binary form. Ram is as follows: mechanical hard disk, solid state hard disk, optical disk and U disk.
- Input devices: keyboard, mouse, microphone, camera, touch screen, scanner, etc.
- Output equipment: display, audio, printer.
- Network equipment: network card
Classification of software:
System software: it is responsible for managing various independent hardware in the computer system so that they can work in coordination. System software enables computer users and other software to treat the computer as a whole without considering how each hardware at the bottom works. It is mainly a set of instructions used to control and manage the underlying hardware.
Provide users with the most basic computer functions.
It includes the following four categories:
- Various service procedures, such as diagnostic procedures, troubleshooting procedures, practice procedures, etc
- Language programs, such as assembler, compiler and interpreter
- operating system
- Database management system
Application software: software developed for a specific purpose based on system software. It can be a specific program, such as an image browser. It can also be a collection of programs with closely related functions and can cooperate with each other, such as Microsoft's Office software. It can also be a huge software system composed of many independent programs, such as database management system.
1.2 human computer interaction mode
- Graphical interface operation mode: simple operation, intuitive performance, easy to operate, cumbersome steps and large space (display icons and other resource files)
- Command line operation mode cmd (Command win+R input cmd enter) window: the operation is complex, there are many commands, it is not easy to start, the steps are simple, the occupied space is small, and it is suitable for remote operation
Common DOS commands:
- cd: change the current directory
Format: cd [/D] [drive:][path]
If the path and subdirectory name are omitted, the current directory is displayed c: get into C Packing directory cd / Enter the root directory of the current drive letter; cd .. Return to the previous directory
- dir: display disk directory command
Format: dir [drive letter] [path] [file name] [/ p][/w][/A [[:] attribute]] [/ O [:] sort order]] [/ S] - cls: clear screen
- md: create subdirectories
Format: md [drive letter:] [pathname] ("subdirectory name")
Drive letter: Specifies the letter of the disk drive to create a subdirectory. If omitted, it is the current drive Pathname: the parent directory name of the subdirectory to be created. If it defaults, it will be created under the current directory md c:\ fox (On current drive c Create subdirectory under disk fox) md c:\ fox\user (stay fox Re create subdirectory user (subdirectories)
- rd: delete subdirectory command
The subdirectory must be empty before deletion, that is, you need to enter the subdirectory first. You cannot delete the root directory and the current directory - Copy: file copy command
Format: copy [source disk] [path] (source file name) [target disk] [path] (target file name) - ren: File Rename command
Format: ren [drive letter:] [path] [ old file name ][ new file name ] - del: delete file command
Format: del [drive letter:] [path] = "file name [/ p]
Select the / p parameter, and the system will ask whether to delete the file before deleting. If this parameter is not used, it will be deleted automatically
Wildcards can be used in file names
If you want to delete all files on the disk (del * · * or del ·), you will be prompted: (are you sure?) Are you sure If you answer y, delete it; if you answer n, cancel the deletion
1.3 computer language
The computer itself is composed of a series of physical hardware. The communication mode between them is electrical signal, high and low voltage - binary data. Therefore, when dealing with computers, we have to do it through binary. Early programming languages / commands existed in binary form
There are many kinds of computer languages. Generally speaking, they can be divided into three categories: machine language, assembly language and high-level language.
- Static compilation language: C, C + +, Java
Compilation refers to the "translation" of the program source code into the object code (machine language) before the execution of the application source program. Therefore, the object program can be executed independently from its language environment, which is more convenient and efficient. However, once the application needs to be modified, the source code must be modified first, and then recompiled to generate a new object file for execution. It is very inconvenient to modify only the object file without the source code. (translate a Book) - Dynamic interpretation language: Python, JS
The execution method is similar to the "simultaneous translation" in our daily life. The source code of the application program is "translated" into the object code (machine language) by the interpreter of the corresponding language and executed at the same time. Therefore, the efficiency is relatively low, and the executable file that can be executed independently cannot be generated. The application program cannot be separated from its interpreter, but this method is relatively flexible and can be adjusted dynamically Modify the application. (simultaneous translation)
1.4 introduction to Java language
Oak, the predecessor of Java language, is an embedded programming language developed by James Gosling and his team in 1994. With the development of the Internet, following the trend of programming, Internet application development language (object-oriented), until Sun was acquired by Oracle in 2010, and Java was a sub product of Oracle.
java Technology Architecture:
- Javase Java Standard Edition: desktop applications
- Java EE Java Enterprise Edition: server applications
- JavaME Java Micro Edition Java Micro Edition: embedded applications
The biggest feature of Java -- cross platform
Cross platform means that a software can run on multiple platforms without changing the content of the software.
Because of the credit of the JVM: the JVM (Java Virtual Machine) Java Virtual Machine.
The suffix of Java source code file is XXX The suffix of binary file compiled by Java is XXX class
JVM is a tool software that is mainly responsible for converting bytecode files of java language into local operating system instructions.
Therefore, the final bytecode file is cross platform!
1.5 establishment of java development environment
JRE and JDK
JRE (Java Runtime Environment): if our computer only wants to run Java programs, install this software. JRE = JVM + core class library.
JDK (Java Development Kit): if our computer wants to develop a Java program, install the software. JDK = Development Tools + JRE.
2, Basic data types and operations
2.1 keywords
Keywords refer to some words with special meaning given by high-level programming language. Keywords are generally composed of lowercase letters.
- Keywords used to define data types: byte short int long float double char boolean void class interface
- Keywords used to define data type values: true false null
- Keywords used to define process control statements: if else switch case default while do for break continue return
- Keywords used to define access modifier: public protected private
- Keywords used to define inheritance relationships: extends implements
- Keywords used to define instance objects: new this super instanceof
- Keyword used to define function type: static final abstract synchronized
- Keyword for handling exceptions: try catch finally throw throws
- Keywords for packages: package import
- Other modified Keywords: native assert volatile transient
2.2 identifier
Identifiers refer to the names of variables, functions, classes, interfaces and constants defined in the program, that is, these names are customized by us.
The rules are as follows:
- Identifiers can consist of numbers, letters, underscores Dollar sign $composition
- Identifiers cannot start with numbers. Of course, underscores and dollar characters can start, but they are not recommended
- Identifier cannot be a keyword
- Identifiers are strictly case sensitive
- The identifier can be any length, but it must be a continuous word
- The identifier cannot also be the name of a Java built-in class
Specification for identifier naming:
- Large hump type: mainly for class name and interface name. Capitalize all words
- Small hump: mainly for variable name and function name. All words except the first one are capitalized
- Constant specification: all words are capitalized, and words are separated by underscores
- Package name specification: all words are in lowercase, and a period is used between words separate
2.3 notes
Comments are used to annotate and explain the built-in text information in some programs of the program, but these built-in text do not belong to the scope of code. Therefore, when compiling the source code with comments, the generated bytecode does not contain comments.
- Single line comment: / / comment content until line break
- Multi line comment: / * line wrapping can be performed inside the comment content*/
- Document comments: / * * the contents of the comments can be wrapped inside * /: the document comments can be recognized by the compiler and generate the corresponding program specification. When generating documents for a class, the class must be public
Multiline comments cannot appear in multiline comments
2.4 constants and hexadecimals
Constant refers to some data directly appearing in the program, also known as literal quantity.
- integer constant
- Decimal constant
- Character constant: data identified by a single quotation mark (') of letters, numbers and symbols
- String constant: data identified by several letters, numbers and symbols in double quotation marks ("")
- Boolean type constant
- null literal
public class Sample { public static void main(String[] args) { //integer constant System.out.println(10); //Decimal integer System.out.println(0b1001); //Binary integers are printed in decimal System.out.println(0123); //Octal integer System.out.println(0xAF3); //Hexadecimal integer //Decimal constant System.out.println(3.14); System.out.println(5.234e3); System.out.println(1.2e-3); //character constants System.out.println('a'); //System.out.println('ab'); ERROR System.out.println('9'); //System.out.println('12'); ERROR System.out.println('I'); System.out.println(' '); //System.out.println(''); ERROR //System.out.println('''); ERROR System.out.println('\''); //'print' System.out.println('\n'); //Print wrap System.out.println('\t'); //Print indent //string constant System.out.println("abcd"); System.out.println("a"); System.out.println(""); //Empty string vs null string System.out.println("\""); //Boolean Literals System.out.println(true); System.out.println(false); } }
Binary to decimal
The law is: 1 1 1 1 1 1 1 1 1 - 128 64 32 16 8 4 2 1
10010101 decimal is 128 + 16 + 4 + 1 = 149
Decimal 149 = 9 * 10 ^ 0 + 4 * 10 ^ 1 + 1 * 10 ^ 2
Binary 1011 = 1 * 2 ^ 0 + 1 * 2 ^ 1 + 0 * 2 ^ 2 + 1 * 2 ^ 3 = 1 + 2 + 0 + 8 = 11
A binary bit is called a bit; Eight bits are called a byte; A byte is the smallest counting unit in a computer.
- 1 byte = 8 bit
- 1 kb = 1024 byte
- 1 mb = 1024 kb
- 1 gb = 1024 mb
Decimal to binary
- 53 ÷ 2 = 26 ~ 1
- 26 ÷ 2 = 13 ~ 0
- 13 ÷ 2 = 6 ~ 1
- 6 ÷ 2 = 3 ~ 0
- 3 ÷ 2 = 1 ~ 1
- 1 ÷ 2 = 0 ~ 1
Remainder from bottom to top 110101 = 1 + 4 + 16 + 32 = 53
Binary to octal
10010101 => 010-010-101 => 0225 = 5 * 8^0 + 2 * 8^1 + 2 * 8^2 =5 + 16 + 128 = 149
Binary to hexadecimal
10010101 => 1001-0101 => 0x95 = 5 * 16^0 + 9 * 16^1 = 5 + 144 = 149
Negative binary
-The binary of 29 takes the binary of the positive part first and then adds 1, which is the binary of the negative number
00011101 = > reverse 11100010 = > add 1 11100011
2.5 variables
- The essence of variable is a temporary storage area in the process where the program is located in memory
- The storage value of this area is limited
- The variation of the area value must be of the same type or downward compatible
- This area has its own physical memory address pointer
The limit of stored values and the change type of data in this area are determined by the data type
The allocation of space and the physical memory address of space in this area are determined by the bottom of the computer
#include<stdio.h> void main() { int a = 3; //Create an ordinary integer variable and store 3 this constant int* b; //Create a single pointer variable and store the address of a variable b = &a; int** c; //Create a double pointer variable and store the address of the b variable c = &b; printf("a Address:%d\n",&a); //Print a's address 0x123 printf("a Contents:%d\n",a); //Print the contents of space a 3 printf("b Address:%d\n",&b); //0x456 printf("b Contents:%d\n",b); //0x123 printf("Take it b Find variables for the contents of a: %d\n",*b); //3 printf("c Address:%d\n",&c); //0x789 printf("Take it c Find variables for the contents of b: %d\n",*c); //0x123 printf("Take it c Find variables for the contents of b,Take it b Find variables for the contents of a: %d\n",**c); //3 //printf("%d\n",*a); printf("%d\n",*&*c); //0x123 printf("%d\n",&*&**&c); //0x456 //give the result as follows a Address: 6422300 a Content: 3 b Address: 6422296 b Content: 6422300 Take it b Find variables for the contents of a: 3 c Address: 6422292 Take it c Find variables for the contents of b: 6422300 Take it c Find variables for the contents of b,Take it b Find variables for the contents of a: 3 6422300 6422296 }
2.6 data type
In Java, data types are mainly divided into two categories: basic data types and reference data types
Basic data type: store data in variable space
- integer
- byte 1 byte 2 ^ 8 256 - 128 ~ 127 - 2 ^ 7 ~ 2 ^ 7 - 1
- short 2 bytes 2 ^ 16 65536 - 32768 ~ 32767 - 2 ^ 15 ~ 2 ^ 15 - 1
- int 4 bytes
- long 8 bytes
- float
- float 4 bytes
- double 8 bytes
- character
- char 2 bytes
- Boolean type
- boolean uncertainty
In constants, integer constants are of type int by default, and decimal constants are of type double by default.
Boolean type. If it is a single variable, true is considered as 1 in the JVM and false is considered as 0, so it is stored in 4 bytes. If it is a boolean type array, true and false are considered as 1 byte of byte type in the JVM
Reference data type: data is stored in heap memory, and variables only store the address of data in heap memory
- character string
- array
- array
In Java, all data stored in heap memory is collectively referred to as objects
2.7 operators
Arithmetic operator | meaning | remarks |
---|---|---|
+ | addition | If there is a string around the plus sign, the plus sign is the connector |
- | subtraction | 6-3=9 |
* | multiplication | 6*6+36 |
/ | division | 3 / 2 = 1 3.0 / 2 = 1.5 if both sides of the division sign are integers, the result is an integer; If there is a decimal, the result is a decimal |
% | Surplus | 9%5=4,x%-y=x%y,-x%y=-(x%y),-x%-y=-(x%y) |
a++ | Post self increasing | a adds one to itself and uses the original value |
++a | Pre self increasing | a adds one to itself and uses the added value |
a– | Post self subtraction | a itself minus one, using the original value |
–a | Pre subtraction | a itself minus one, use the value after adding |
Assignment Operators
-
+=
-
-=
-
*=
-
/=
-
%=
Comparison operator -
>
-
<
-
>=
-
<=
-
!=
Logical operator
- &
- !
- ^
- !
- &&
- ||
Bitwise Operators
- &And
- |Or
- ^XOR (difference is 1, same is 0)
- >>Shift right (decrease * 2^x)
- < < shift left (increase * 2^x)(x is the offset)
ternary operator
Data type variable name = Boolean expression? Value 1: value 2;
int number = 10 % 2 == 0? 10 : 2;
Exchange of variables:
int a = 3;int b = 7;
//Method 1 int c = a; a = b; b = c; System.out.println(a); System.out.println(b); //Method 2 a = a + b; b = a - b; a = a - b; System.out.println(a); System.out.println(b); //Method 3 a = a ^ b; b = a ^ b; a = a ^ b; System.out.println(a); System.out.println(b);
3, Process control statement
3.1 if conditional statement
Single branch if statement
...CodeA if (Boolean expression) { Statement group; } ...CodeB
Double branch if else statement
...CodeA if (Boolean expression) { Statement group A; } else { Statement group B; } ....CodeB
Multi branch if else if statement
...CodeA if (Boolean expression 1) { Statement group A; } else if (Boolean expression 2) { Statement group B; } else if (Boolean expression 3) { Statement group C; } else { Statement group D; } ...CodeB
3.2 switch branch statement
Like the if branch statement, it is the judgment of conditions. Switch is generally used when there are many conditions, but there is an important detail. If language can judge interval values or fixed values, while switch can only judge fixed values.
switch (variable) { case Value 1: //if (variable = = value 1) {statement group A;} Statement group A; break; case Value 2: Statement group B; break; ... case value n: //if (variable = = value n) {statement group N;} Statement group N; default: // else {statement group N+1;} Statement group N+1; break; }
Some usage details of switch
- The variable passed in by switch, char, byte, short, int, String or enumeration type
- Value 1, value 2, up to value n, these values must be of the same data type
- When the variable matches the value of the relevant case, execute the statements in the case until the end of break is encountered; If there is no break in the case statement, continue to execute downward until another break is encountered
3.3 for loop statement
Loop mainly solves the problem of regular and repetitive code to avoid program redundancy
Four elements of circulation
- 1 loop initialization: where does the first execution of the loop start
- 2. Continuation condition of the cycle: whether the cycle executes the next round backward from the current round
- 3 loop body: the part that needs to be executed by the loop
- 4 cycle step and cycle: the change from the current cycle to the next cycle
Common circular problems can be divided into two categories:
- If the number of cycles is known, it is generally done with the for statement
- The number of cycles is unknown, but the loop end condition is known. Generally, the while statement is used
for (1 Initialization of loop;2.Continuation condition of cycle;4.Step size of the loop) { 3.Circulatory body } 1-2-3-4-2-3-4-2-3-4-2 If not, end the cycle
3.4 while loop statement
The while loop is mainly used to solve the situation where the number of cycles is unknown but the end condition of the loop is known.
In fact, while and for loops can be converted to each other because they cannot escape the four elements of the loop
1.Initialization of loop while (2.Cycle continuation condition) { 3.Circulatory body 4.Step and period of cycle }
for (int i = 1; i <= 5; i++) { System.out.println(i); } Can be converted to while loop int i = 1; while (i <= 5) { System.out.println(i); i++; }
3.5 break and continue jump statements
Break is called a termination statement in a loop statement. It terminates the closest loop to break
continue is called a skip statement in a loop statement. Skip this loop and start the next loop
3.6 programming exercises
Idea: generate a two digit number randomly in the background, obtain the ten and one digits that generate two digits, and compare them with the numbers entered by the user to obtain the bonus.
import java.util.Scanner; public class Demo19{ public static void main(String[] args){ //Generate the random number of [10100], and obtain the ten bits and the one bits of the number respectively int number = (int)(Math.random()*90 + 10); int numberShi = number / 10; int numberGe = number % 10; //Obtain the number entered by the user, and obtain the ten and ten bits of the number respectively Scanner input = new Scanner(System.in); System.out.print("Please enter a two digit number:"); int guess = input.nextInt(); int guessShi = guess / 10; int guessGe = guess % 10; //Judge the bonus won by users according to the situation if(number == guess){ System.out.println("Bonus $10000"); }else if(numberShi == guessGe && numberGe == guessShi){ System.out.println("Bonus $3000"); }else if(numberShi==guessShi || numberGe == guessGe){ System.out.println("Bonus $1000"); }else{ System.out.println("Didn't win the prize"); } System.out.println("The winning number is:" + number); } }
Idea: judge whether AD BC is equal to 0 according to the data entered by the user. If it is 0, the program will end and the prompt information will be output. Otherwise, the data will be brought into the formula for calculation.
import java.util.Scanner; public class Demo21{ public static void main(String[] args){ Scanner scanner=new Scanner(System.in); System.out.print("Enter a,b,c,d,e,f: "); double a=scanner.nextDouble(); double b=scanner.nextDouble(); double c=scanner.nextDouble(); double d=scanner.nextDouble(); double e=scanner.nextDouble(); double f=scanner.nextDouble(); //Judge whether the data entered by the user has a value. If there is a value, it will be carried into formula calculation if((a * d - b * c)==0){ System.out.println("The equation has no solution"); } else{ double x=(e * d - b * f) / (a * d - b * c); double y=(a * f - e * c) / (a * d - b * c); System.out.println("x is "+x+" and y is "+y); } } }
Idea: add the weeks and days entered by the user, take the remainder of 7, and judge the weeks of future days according to the remainder.
import java.util.Scanner; public class Demo22{ public static void main(String[] args){ Scanner scanner=new Scanner(System.in); //Get the week and days after the date of today entered by the user System.out.print("Enter today's day: "); int day=scanner.nextInt(); System.out.print("Enter the number of days elapsed since today: "); int latter=scanner.nextInt(); //Add the data entered by the user, and judge the week according to the remainder after taking the remainder of 7 int finall=(day + latter) % 7; String today=process(day); //If the input number exceeds the range, the user will be prompted that the input is invalid if(today=="error"){ System.out.println("Check the nubmer you jiust hava input!"); } else{ System.out.println("Today is "+process(day)+" and the future day is "+process(finall)); } } public static String process(int day){ String week=""; switch(day) { case 0: week="Sunday"; break; case 1: week="Monday"; break; case 2: week="Tuesday"; break; case 3: week="Wednesday"; break; case 4: week="Thursday"; break; case 5: week="Friday"; break; case 6: week="Saturday"; break; default: week="error"; } return week; } }
Train of thought: the train of thought is basically similar to the previous question. Just bring the data entered by the user into the formula calculation.
import java.util.Scanner; public class Demo25{ public static void main(String[] args){ //Get the data entered by the user Scanner scanner=new Scanner(System.in); System.out.print("Enter year: (e.g..2012): "); int year=scanner.nextInt(); System.out.print("Enter month: (1-12): "); int month=scanner.nextInt(); System.out.print("Enter the day of month: (1-31): "); int day=scanner.nextInt(); //If the month is 1 or 2, change the month to 13 and 14 respectively, and change the year to 1 if(month==1 || month==2){ month+=12; year-=1; } //Bring in formula calculation int j=year / 100; int k=year % 100; int weekInt=(day + 26 * (month + 1) / 10 + k + k / 4 + j / 4 + 5 * j) % 7; String week=process(weekInt); System.out.println("Day of the week is "+week); } public static String process(int day){ String week=""; switch(day) { case 0: week="Sunday"; break; case 1: week="Monday"; break; case 2: week="Tuesday"; break; case 3: week="Wednesday"; break; case 4: week="Thursday"; break; case 5: week="Friday"; break; case 6: week="Saturday"; break; default: week="error"; } return week; } }
Idea: obtain the coordinates of the user input point, judge the relationship between the coordinates and the width and height of the rectangle, and get whether the point is in the rectangle.
import java.util.Scanner; public class Demo27{ public static void main(String[] args){ Scanner scanner=new Scanner(System.in); System.out.print("Enter a point with two coordinates: "); double i=scanner.nextDouble(); double j=scanner.nextDouble(); //Calculate the absolute value of the coordinates entered by the user double x=Math.abs(i); double y=Math.abs(j); //Judge the distance between the point and the width and height of the rectangle if((x < (10 / 2)) && (y < (5.0 / 2))){ System.out.println("Point ("+i+", "+j+") is in the rectangle"); } else{ System.out.println("Point ("+i+", "+j+") is not in the rectangle"); } } }
Idea: draw the critical value of two rectangles early, and the data relationship of the critical value can be obtained.
import java.util.Scanner; public class Demo29{ public static void main(String[] args){ System.out.print("Enter r1's center x-,y-coordinates,width, and height: "); Scanner scanner=new Scanner(System.in); double x1=scanner.nextDouble(); double y1=scanner.nextDouble(); double w1=scanner.nextDouble(); double h1=scanner.nextDouble(); //Get the coordinates of the center points of the two rectangles entered by the user, and the width and height of the rectangle System.out.print("Enter r2's center x-,y-coordinates,width, and height: "); double x2=scanner.nextDouble(); double y2=scanner.nextDouble(); double w2=scanner.nextDouble(); double h2=scanner.nextDouble(); //Judge the relationship between the critical value and draw a conclusion if(y2 -y1 <= (h1 - h2) / 2 && y1 -y2 <= (h1 - h2) / 2 && x2 -x1 <= (w1 - w2) / 2 && x1 -x2 <= (w1 -w2) / 2) { System.out.println("r2 is inside r1"); }else if(y2 -y1 >= (h1 + h2) / 2 || y1 -y2 >= (h1 + h2) / 2 || x2 -x1 >= (w1 + w2) / 2 || x1 -x2 >= (w1 + w2) / 2) { System.out.println("r2 does not voerlap r1"); }else { System.out.println("r2 overlaps r1"); } } }
Idea: after the user inputs the coordinates and the center of the circle, calculate the center distance between the two circles, and compare the center distance with the two radii to obtain the position relationship of the two circles.
import java.util.Scanner; public class Demo30{ public static void main(String[] args){ //Obtain the entered coordinates and center data System.out.print("Please enter the coordinates and radius of the circle 1 Center:"); Scanner input=new Scanner(System.in); double ox1=input.nextDouble(); double oy1=input.nextDouble(); double r1=input.nextDouble(); System.out.print("Please enter the coordinates and radius of the circle 2 Center:"); double ox2=input.nextDouble(); double oy2=input.nextDouble(); double r2=input.nextDouble(); //Calculate center distance double distant=Math.sqrt(Math.pow(ox1 - ox2,2) + Math.pow(oy1 -oy2,2)); //judge the distance if(distant <= r1 - r2){ System.out.println("Circle 2 is in circle 1"); }else if(distant < r1 +r2){ System.out.println("Circle 2 intersects circle 1"); }else{ System.out.println("Circle 2 is outside circle 1"); } } }
Idea: get the two input numbers, compare the size of the two numbers, take the smallest value as the initial value of the cycle, and traverse in reverse order. Each traverse determines whether the number can be divided by the two input numbers. If so, the number is the maximum common divisor. End the cycle and output. Otherwise, continue to traverse and find.
import java.util.Scanner; public class Demo33{ public static void main(String[] args){ //Enter two numbers and take out the minimum value, System.out.print("Please enter two integers:"); Scanner input=new Scanner(System.in); int num1=input.nextInt(); int num2=input.nextInt(); //Gets the smaller of two values int min=num1 < num2 ? num1 : num2; int gcd=1; //The lowest value of M1 and num2 can be found one by one for(int i=min;i>0;i--){ if(num1 % i == 0 && num2 % i == 0){ gcd=i; break; } } System.out.println("The maximum common divisor is:"+gcd); } }
Idea: for the characters in the string, you can use string Charat (index) method to obtain the value of the index subscript in the string. Therefore, you can judge whether the string is a palindrome string by comparing the values at the beginning and end of the string. Set the left as l,l starts from 0, l=0, and r=str.length()-1 on the right. The condition for judging the end is l < R, that is, the loop ends when the subscript on the left is greater than that on the right.
import java.util.Scanner; public class Demo35{ public static void main(String[] args){ System.out.print("Please enter a paragraph:"); Scanner input=new Scanner(System.in); String str = input.nextLine(); int l=0; int r=str.length()-1; boolean flag=true; //Determine whether the string is palindrome at the beginning and end while(l < r){ if(str.charAt(l) == str.charAt(r)){ l++; r--; }else{ flag = false; break; } } if(flag) { System.out.println(str + "This passage is a palindrome"); }else { System.out.println(str + "This paragraph is not a palindrome"); } } }
Idea: five lines display 50 prime numbers. Take 50 as the cycle condition, define a counter variable, and wrap every 10 lines. Starting from 2, the cycle judges whether the number can be divided by each number of half of the number. It can not be processed. The next number in the cycle, otherwise, the number will be output and the counter will be incremented by 1.
public class Demo36{ public static void main(String[] args){ int count=0; int number=2; while(count < 50){ //Indicates whether the number is a prime number boolean flag=true; for(int i=2; i<=number / 2; i++) { if(number % i ==0){ flag=false; break; } } //The counter is incremented by 1, and the prime number is output. Every ten lines are wrapped if(flag) { System.out.print(number + "\t"); count++; if(count % 10 ==0) { System.out.println(); } } number++; } } }
Idea:
Line 4 4 3 2 1 2 3 4
3 2 1 0 1 2 3
y = |x| + 1 x∈[-3,3]
Line 5 5 4 3 2 1 2 3 4 5
4 3 2 1 0 1 2 3 4
y = |x| + 1 x∈[-4,4]
Line I y = |x| + 1 x ∈ [- (i-1),i-1]
public class Demo41{ public static void main(String[] args){ //A total of 7 cycles for(int i=1; i <= 7; i++) { //Print the space first each time, and the space rule is 7-i for(int k=1; k<= 7-i; k++) { System.out.print(" "); } for(int j=-(i-1); j<=i-1; j++) { System.out.print(Math.abs(j)+1+" "); } System.out.println(); } } }
Idea: the cycle carries out an accumulation, and the denominator is numerator + 2
public class Demo45{ public static void main(String[] args){ double sum=0; //The step of cyclic accumulation is 2 for(int i=1; i<=97; i+=2) { sum += i * 1.0 / (i+2); } System.out.println(sum); } }
Idea: cycle accumulation and find the factorial of each time. Each factorial is the previous factorial multiplied by the number of current cycles. (the order multiplier in the question is too large, which is larger than the range of int and double, and the result is infinite, so the range is narrowed here)
public class Demo47{ public static void main(String[] args){ double sum = 1; //The value cannot be 10000. If the factorial range exceeds the int range, the result will be infinite int max = 10; //The order multiplier starts with 1 int temp = 1; for(int i=1; i < max; i++) { temp=temp * i; sum += 1.0 / temp; } System.out.println(sum); } }
Idea: cycle from 1 to 10000, and the inner cycle starts from 1 to the half value of the number each time. Judge whether the number of the current inner cycle can be divided by the number of the outer cycle. If possible, add the sum. After the inner cycle is completed, judge whether the sum is equal to the current value, and output it if it is equal. Otherwise, continue the cycle.
public class Demo48{ public static void main(String[] args){ for(int i=1; i<=10000; i++) { int sum=0; //Judge whether the current number can be divided by the number from 1 to half, and add the sum if possible for(int j=1; j<=i / 2; j++) { if(i % j == 0) { sum +=j; } } //If the sum is equal to the current number, the result is output if(sum == i) { System.out.print(i+"\t"); } } } }
Idea: take the number of times the user or computer wins as the exit condition of the cycle. As long as the user or computer wins twice, he or she will exit the cycle. Each time he or she enters the cycle, he or she will receive the number entered by the user and generate an internal random number. After comparing the two numbers, judge whether he or she wins or loses, and enter the counter of the user and computer, After reaching twice, the cycle is ended to judge whether the user wins or the computer wins.
import java.util.*; public class Demo49{ public static void main(String[] args){ //Define an array of strings String[] arry={"scissors","stone","cloth"}; Scanner input =new Scanner(System.in); //A counter that defines the number of times users and computers win int userCount = 0; int comCount = 0; //As long as the number of wins won by users and computers is not 2, the cycle continues while(userCount != 2 && comCount != 2){ System.out.print("scissors(0),stone(1),cloth(2):"); int user=input.nextInt(); Random random=new Random(); //Randomly generate a number of [0,3) int com=random.nextInt(3); //Judge who wins between the user and the computer and record it in the counter if(user == com) { System.out.println("User:"+arry[user]+" , computer:"+arry[com]+", it ends in a draw!"); }else if(user - com == -2 || user - com == 1 ) { System.out.println("User:"+arry[user]+" , computer:"+arry[com]+", Users win!"); userCount++; }else { System.out.println("User:"+arry[user]+" , computer:"+arry[com]+", Computer wins!"); comCount++; } } if(userCount == 2) { System.out.println("The user finally wins!"); } else { System.out.println("The computer finally wins!"); } } }
Idea: take the remainder of 2 in each cycle, store the remainder in the first bit of the string, and then divide by 2 to remove the last digit until it is 0.
import java.util.Scanner; public class Demo50{ public static void main(String[] args){ System.out.print("Please enter a number:"); Scanner input = new Scanner(System.in); int number = input.nextInt(); String str=""; //Take the remainder of 2 each time and store the number in the first bit of the string while(number != 0){ str = number % 2 + str; number /= 2; } System.out.println(str); } }
Idea: the same idea as binary.
import java.util.Scanner; public class Demo51{ public static void main(String[] args){ System.out.print("Please enter an integer:"); Scanner input = new Scanner(System.in); int number = input.nextInt(); String o = ""; //Take the remainder of 8 each time and store the number in the first bit of the string while(number != 0) { o = number % 8 +o; number /= 8; } System.out.println(o); } }
Idea: dead loop: get a value of a string of numbers each time, compare the initial maximum value of 0, assign the value to the maximum value if it is greater than, and set the counter to 1. If it is equal to the maximum value, add one to the counter, cycle until the input is 0, and finally output the result.
import java.util.Scanner; public class Demo52{ public static void main(String[] args){ System.out.print("Please enter a string of integer numbers:"); Scanner input = new Scanner(System.in); int max=0; int count=0; while(true) { //Dead loop, one number at a time, ending with 0 int num=input.nextInt(); if(num == 0){ break; } //Judge whether the current number is greater than the maximum number. If yes, assign the modified value to the maximum value and set the counter to 1 if(num > max){ max=num; count=1; //If it's equal, add it first }else if(num == max){ count++; } } //Final output result if(max == 0){ System.out.println("none"); }else { System.out.println("max number is "+max+" is count is "+count); } } }
Train of thought: basic logical train of thought
import java.util.Scanner; public class Demo31{ public static void main(String[] args){ Scanner scanner=new Scanner(System.in); System.out.print("Enter an integer: "); int num=scanner.nextInt(); //And judgment, which can be divided by 5 and 6 if(num % 5 == 0 && num % 6 == 0){ System.out.println("Is "+num+"divisible by 5 and 6?"+" true"); }else{ System.out.println("Is "+num+"divisible by 5 and 6?"+" false"); } //Or judgment, can be divided by 5 or 6 if(num % 5 == 0 || num % 6 == 0){ System.out.println("Is "+num+"divisible by 5 or 6?"+" true"); }else{ System.out.println("Is "+num+"divisible by 5 or 6?"+" false"); } //XOR judgment cannot be divided by 5 or 6 at the same time if(num % 5 == 0 ^ num % 6 == 0){ System.out.println("Is "+num+"divisible by 5 and 6, but not both?"+" true"); }else{ System.out.println("Is "+num+"divisible by 5 and 6, but not both?"+" false"); } } }
Idea: cycle the input decimal number to take the remainder of 16. If the remainder is less than 10, directly convert the number into character numbers, otherwise it will become the corresponding a, B, C, D, e and F, and store it in a character array. After the cycle, output the character array in reverse order.
import java.util.Scanner; public class Demo34{ public static void main(String[] args){ Scanner scanner=new Scanner(System.in); System.out.print("Please enter an integer:"); int num=scanner.nextInt(); int i=0; //Define a character array to store hexadecimal characters char[] ch=new char[100]; //If it is 0, it will be output directly if (num==0) { System.out.println(0); }else{ while(num!=0){ //Loop to take the remainder of 16. If it is less than 10, it will become A character. If it is greater than 10, add A character and subtract 10 to change it into hexadecimal character int n=num % 16; if(n < 10){ ch[i++]=(char) (n+'0'); } else{ ch[i++]=(char) (n+'A'-10); } num /= 16; } } //Output the character array in reverse order for(int j=i-1;j>=0;j--){ System.out.print(ch[j]); } } }
Idea: first define positive numbers, negative numbers, the number of input numbers, and the sum. The average value is initially 0. Cycle to obtain the number input by the user. Judge with 0 that > 0 positive number plus one, add the sum, add the number of input numbers plus 1, < 0 negative number plus one, add the sum, and add the number of input numbers plus 1. After the cycle, calculate the average and output the result.
import java.util.Scanner; public class Demo37{ public static void main(String[] args){ Scanner scanner=new Scanner(System.in); //The initial value of the definition is 0 int temp=0,positNum=0,negatNum=0,total=0,sum=0; System.out.print("Enter an interger, the input ends if it is 0:"); //Judge the size of the input number and count it into the total while((temp=scanner.nextInt())!=0){ if(temp > 0){ positNum++; } if(temp < 0){ negatNum++; } sum += temp; total++; } //Output results if(total==0){ System.out.println("No numbers are entered except 0"); }else{ double avg=sum / total; System.out.println("The number of positives is "+positNum); System.out.println("The number of negatives is "+negatNum); System.out.println("The total is "+sum); System.out.println("The average is "+avg); } } }
Idea: cycle to judge the number that can be divided by 5 and 6, count and change the line every 10.
public class Demo38{ public static void main(String[] args){ //The counter wraps every 10 lines int j=0; //Circular judgment finds the number that can be divided by 5 and 6 for(int i=100;i <=1000;i++){ if(i % 5==0 && i % 6==0){ System.out.print(i+" "); j++; } if(j % 10 ==0){ j=0; System.out.println(); } } } }
Idea: define a string to save the factor of the input number, judge whether the input number is 1, and output an empty string if yes. Otherwise, take the remainder of the number from 2. If the remainder is 0, store the factor in the string, and assign the number of / 2 to the number to continue the cycle. If not, it will be traversed automatically.
import java.util.Scanner; public class Demo40{ public static void main(String[] args){ System.out.print("Enter an integer:"); Scanner input=new Scanner(System.in); String result=""; int num=input.nextInt(); //The number of factors starts from 2, and the number entered is not 1 for(int i = 2;num != 1;) { if(num % i == 0) { num /= i; result += i + ", "; }else { i++; } } //Output results System.out.println("The minimum number of factors is: "+result); } }
Idea: Line 4
4 3 2 1 2 3 4
3 2 1 0 1 2 3
y = |x| + 1 x∈[-3,3]
Line 5
5 4 3 2 1 2 3 4 5
4 3 2 1 0 1 2 3 4
y = |x| + 1 x∈[-4,4]
Line I y = |x| + 1 x ∈ [- (i-1),i-1]
public class Demo41 { public static void main(String[] args) { for (int i = 1; i <= 7; i++) { for (int k = 1; k <= 7 - i ;k++) { System.out.print(" "); } for (int j = -(i - 1); j <= i - 1; j++) { System.out.print(Math.abs(j) + 1 + " "); } System.out.println(); } } }
Idea: pattern 1: print the number of the current cycle on each line from 1 to 6
Pattern 2: the reverse order of pattern 1
Pattern 3: print | i-6 | spaces first when printing lines
Pattern 4: on the basis of pattern 3, the number of inner cycles starts from 1 to the end of outer cycles
public class Demo42{ public static void main(String[] args){ //Cycle 6 lines, printing i numbers per line for(int i=1;i<=6;i++){ for(int j=1;j<=i;j++){ System.out.print(j+" "); } System.out.println(); } System.out.println("----------------"); //Reverse order output for(int i=6;i>=0;i--){ for(int j=1;j<=i;j++){ System.out.print(j+" "); } System.out.println(); } System.out.println("----------------"); //Print | i-6 | spaces per line for(int i=1;i<=6;i++){ for(int k=1;k<=Math.abs(i-6);k++){ System.out.print(" "); } for(int j=i;j>0;j--){ System.out.print(j+" "); } System.out.println(); } System.out.println("----------------"); //The reverse order of internal circulation from 1 to i for(int i=6;i>=0;i--){ for(int k=1;k<=Math.abs(i-6);k++){ System.out.print(" "); } for(int j=1;j<=i;j++){ System.out.print(j+" "); } System.out.println(); } } }
Idea: the ascending power of each behavior 2 starting from 0, and find out the range of internal circulation according to the law
Line 1 0
Line 2 0 1 0
Line 3 0 1 2 1 0
Line 4 0 1 2 3 2 1 0
Line I: F (x) = I - 1 - | x ∈ [- (i-1),i-1]
public class Demo43{ public static void main(String[] args){ //Cycle 8 times, printing 8-i spaces at a time for(int i=1; i<=8; i++) { for(int k=1; k<=8-i; k++){ System.out.print(" "); } for(int j=1 - i; j<= i-1;j++) { int num=(int) Math.pow(2,i -1 -Math.abs(j)); //Each number occupies four spaces and is aligned to the right System.out.printf("%4d",num); } System.out.println(); } } }
Idea: according to the formula, cycle evaluation is enough.
import java.util.Scanner; public class Demo46{ public static void main(String[] args){ double pai=0; double s=0; //Cyclic evaluation for(int i=1;i<=100000;i++){ double temp=Math.pow(-1.0, i + 1) / ( 2 * i - 1); s+=temp; } pai=4 * s; System.out.println(pai); } }
4, Common class
4.1 Math class
Java's Math contains properties and methods for performing basic mathematical operations, such as elementary exponents, logarithms, square roots, and trigonometric functions.
Math methods are defined in static form, and can be called directly in the main function through math class.
Natural constants:
Constant name | meaning |
---|---|
Math.E | Natural logarithm (return double) |
Math.PI | PI (return double) |
Rounding method:
Method name | meaning |
---|---|
Math.ceil(double a) | Round up |
Math.floor(double a) | Round down |
Math.round(double a) | rounding |
Trigonometric function:
Method name | meaning |
---|---|
Math.sin(double a) | The sine function parameter is the radian value |
Math.cos(double a) | cosine |
Math.tan(double a) | tangent |
Math.toDegrees(double a) | Turn the radian to an angle |
Math.toRadians(double a) | Turn the angle to radians |
Math.asin(double a) | Inverse sine function |
Math.acos(double a) | Inverse cosine function |
Math.atan(double a) | Arctangent function |
Exponential function:
Method name | meaning |
---|---|
Math.pow(double a,double b) | a^b |
Math.sqrt(double a) | Square root of a |
Math.cbrt(double a) | Cube root of a |
other:
Method name | meaning |
---|---|
Math.hypot(double a,double b) | Find the distance between two points a and B |
Math.abs(double a) | Absolute value of a |
Math.max(a,b) | Returns the maximum value between a and b |
Math.min(a,b) | Returns the minimum value between a and b |
Math.random() | Produces a decimal between [0,1] |
Scanner class 2.4
It is used for the class responsible for data input. The bottom layer is related to IO flow.
Method name | meaning |
---|---|
String next() | Gets a string until a space is encountered |
String nextLine() | Gets a string until a carriage return is encountered |
int nextInt() | Gets an integer ending with a space |
double nextDouble() | Get a decimal space end |
float nextFloat() | Get a decimal space end |
boolean nextBoolean() | Gets a boolean type ending with a space |
4.3 Random class
Used to generate random numbers
Method name | meaning |
---|---|
int nextInt() | Randomly generate an integer from 0 to 2 ^ 32 |
int nextInt(n) | Generate an integer of [0,n) randomly |
double nextDouble() | Randomly generate a decimal of [0,1] |
boolean nextBoolean() | Randomly generate a Boolean value |
4.4 String class
The String class cannot be changed, so once you create a String object, its value cannot be changed. Its length and content cannot be modified. Therefore, the future changes to the String content cannot be changed in place, but can only recreate a String.
public class Sample { public static void main(String[] args) { String s1 = "abc"; String s2 = "ab" + "dc"; //How many strings are there in the above code? //Four "abc" "ab" "dc" "abdc" } }
obtain:
Method name | meaning |
---|---|
char charAt(int index) | Gets the character at the specified subscript index |
int indexOf(int ch) | Gets where the specified character (encoding) appears for the first time (from left to right) in the string. The corner mark is returned- 1 indicates that it does not exist |
int lastIndexOf(int ch) | Gets the place where the specified character (encoding) appears for the first time (from right to right) in the string, and returns the corner mark |
int indexOf(String str) | Gets where the specified string appears for the first time (from left to right) in this string, and returns the corner mark |
int lastIndexOf(String str) | Gets where the specified string appears for the first time (from right to left) in this string, and returns the corner mark |
int length() | Gets the length of the string |
String[] split(String regex) | Divide the string according to the definition of regex |
String substring(int beginIndex) | Intercept a substring from beginIndex to the end |
String substring(int beginIndex, int endIndex) | Intercept a substring from beginIndex to endindex (excluding) |
Modification:
Method name | meaning |
---|---|
String toLowerCase() | Change all English letters in the string to lowercase |
String toUpperCase() | Change all English letters in the string to uppercase |
String trim() | Remove spaces at both ends of a string |
String replace(char oldCh,char newCh) | Replace the oldCh character in the string with the newCh character |
Judgment:
Method name | meaning |
---|---|
int compareTo(String anotherString) | Compare the size of two strings in dictionary order |
boolean contains(String another) | Judge whether the current string contains the specified string other |
boolean equals(String another) | Compare whether the contents of the current string and the specified string are the same |
boolean isEmpty() | Judge whether the current string is empty |
boolean startsWith(String prefix) | Judge whether the string starts with prefix |
boolean endsWith(String suix) | Determine whether the string has suix ended |
Case 1
How to delete the spaces at the left and right ends of a string without using trim?
Idea: start from both ends of the string, write down the subscript as long as you encounter characters, and finally intercept the string with the subscripts at both ends to remove the spaces on both sides.
public class Sample { public static void main(String[] args) { String str = " 123123123 12123 "; //"12312312123" after removing the space //Define subscripts at both ends int l = 0; int r = str.length() - 1; while (str.charAt(l) == ' ') { l++; } while (str.charAt(r) == ' ') { r--; } //Intercept string with subscript System.out.println("[" + str.substring(l,r + 1) + "]"); } }
Case 2
Count the number of occurrences of "bcb" in the string "abcbc"?
Idea:
After the index of the string is not found, the algorithm counts the non greedy string until the index of the string is found.
Greedy algorithm: cycle a string with a long length for a long string - a short string. Each time you judge whether the first letter of the long string matches the first character of the string to be matched, intercept the long string (the length of the matching string) and compare the count with the string to be matched.
public class Sample { public static void main(String[] args) { String s1 = "abcbcbcbcbcbc"; String s2 = "bcb"; //Greedy algorithm 5 int count = 0; for (int i = 0; i < s1.length() - s2.length() + 1; i++) { if (s1.charAt(i) == s2.charAt(0)) { if (s2.equals(s1.substring(i,i + s2.length()))) { count++; } } } System.out.println(count); //3 non greedy algorithms /* String temp = s1; int count = 0; while (true) { int index = temp.indexOf(s2); if (index == -1) { break; } count++; temp = temp.substring(index + s2.length()); } System.out.println(count); */ } }
Case 3
Find the longest common substring of two strings?
Idea: in a shorter string, define the left and right corner marks, intercept the shorter string each time, compare with the comparison string whether it contains the relationship, and then output it. Otherwise, continue the loop traversal.
public class Sample { public static void main(String[] args) { String s1 = "c is a program but is diffcult"; String s2 = "Java is a program but is slow"; for (int len = s2.length(); len > 0; len--) { for (int l = 0,r = len - 1; r < s2.length(); l++,r++) { String temp = s2.substring(l,r + 1); if (s1.contains(temp)) { System.out.println(temp); return;//End program directly } } } } }
4.5 Character class
Character tool class
Method name | meaning |
---|---|
Character.isDigit(char ch) | Judge whether the character is a number |
Character.isLetter(char ch) | Determine whether the character is a letter |
Character.isLetterOrDigit(char ch) | Determine whether the character is a number or letter |
Character.isLowerCase(char ch) | Determine whether it is lowercase |
Character.isUpperCase(char ch) | Determine whether it is a capital letter |
Character.isSpaceChar(char ch) | Determine whether there is a blank letter (space tab enter) |
Case 1
Convert hexadecimal digits to decimal?
Idea: users input hexadecimal characters and use string tools to judge whether the characters are numbers and letters. If it is a letter, judge whether the letter is within the range of A-F. otherwise, illegal characters will be output. If it is not an illegal character, cycle to count the decimal numbers corresponding to hexadecimal.
import java.util.Scanner; public class Sample{ public static void main(String[] args){ System.out.print("Please enter a hexadecimal number: "); Scanner input = new Scanner(System.in); String hex = input.nextLine().toUpperCase(); //If the input length is 0, there is no input if(hex.length() == 0){ System.out.println("No input!"); return; } //Loop to judge whether the input character is illegal //Exclude non numeric, alphabetic, and non-A-F characters for(int i=0; i<hex.length(); i++) { char ch = hex.charAt(i); if(Character.isDigit(ch) || Character.isLetter(ch)) { if(Character.isLetter(ch) && (ch < 'A' || ch > 'F')) { System.out.println("Illegal character:"+ch); return; } }else { System.out.println("Illegal character:"+ch); return; } } //Loop count hexadecimal decimal number int sum=0; for(int i=hex.length() - 1; i>=0; i--) { char ch = hex.charAt(i); //If it is a number, it is the current number of character - 48 if(Character.isDigit(ch)) { sum += (int) Math.pow(16, hex.length()-i-1) * (ch - 48); }else { //Character - 65 + 10 obtains the decimal number corresponding to the character sum += (int) Math.pow(16,hex.length()-i-1) * (ch - 55); } } System.out.println(sum); } }
4.6 programming exercises
Idea: cycle to take the remainder of 16. After obtaining the remainder, judge whether the remainder is greater than 10. Add + 55 to the part greater than or equal to 10 and convert it into A-F characters. The part less than 10 can be directly spliced into the string. Divide the number of the current cycle by 16 for the next cycle.
import java.util.Scanner; public class Demo59{ public static void main(String[] args) { System.out.print("Please enter a decimal number:"); Scanner input = new Scanner(System.in); int number = input.nextInt(); String hex = ""; //Loop traversal 16 remainder while(number != 0) { int i = number % 16; //If the remainder is greater than or equal to 10, it will be converted to the corresponding A-F, otherwise it will be spliced directly to the beginning of the string if(i >=10) { hex = (char)(i + 55) + hex; }else { hex = i + hex; } number /= 16; } System.out.println(hex); } }
Idea: judge whether the length and characters of the input string meet the requirements. If they do not meet the requirements, exit the program. If they meet the requirements, add the third power of the odd bit of the string to the sum, and the even bit to the sum directly. Calculate the thirteenth number of isbn according to the formula, and then splice the string to return to output.
import java.util.Scanner; public class Demo63{ public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("Enter ISBN-12:"); String isbn = input.nextLine(); //Judge whether the length of the input string is 12 and whether each character is a number. If not, end the program if(isbn.length() != 12) { System.out.println(isbn+" is an invalid input "); return; } for(int i=0; i<isbn.length(); i++) { if(!Character.isDigit(isbn.charAt(i))) { System.out.println(isbn+" is an invalid input"); return; } } int sum = 0; //If it meets the requirements, add the sum of the three times in which the odd number in the string is the power, and the even number is directly added to the sum, which is brought into the formula to calculate the isbn code for(int i=0; i<isbn.length(); i++) { if(i % 2 == 0) { sum = sum + isbn.charAt(i) - 48; }else { sum = sum + 3 * (isbn.charAt(i) - 48); } } int d13 = 10 - sum % 10; if(d13 == 10) { d13 = 0; } System.out.println("The ISBN-13 number is "+isbn+d13); } }
Idea: first judge whether the first character is equal. If not, end the program. Otherwise, cycle to judge whether the first character of two strings is equal. If equal, judge the next character. If not, intercept the string from 0 to the current subscript. str2 is the maximum public prefix by default.
import java.util.Scanner; public class Demo66{ public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a s1: "); String str1 = input.nextLine(); System.out.print("Enter a s2: "); String str2 = input.nextLine(); /* Judge whether the first characters are equal. If they are not equal, no equal prefix will be returned */ if(str2.charAt(0) != str1.charAt(0)) { System.out.println(str1 +" and "+str2+" have no common prefix"); return; } //Otherwise, cycle str2 (the default str2 is the shortest), and compare whether the characters of two strings are equal one by one. If not, intercept the character. The default is str2 boolean flag = true; for(int i=0; i<str2.length(); i++) { if(str1.charAt(i) != str2.charAt(i)) { flag = false; System.out.println(str2.substring(0,i)); break; } } if(flag) { System.out.println("The common prefix is: "+str2); } } }
5, Function
5.1 concept of function
Definition of function: the definition of function refers to a piece of code with independent functions to reduce code redundancy and improve the utilization and efficiency of the program.
Components of function:
- Function name
- Function body
- Function parameters (formal parameters)
- Function return value type
The basic number is as follows:
Modifier function type return value type function name(Data type data 1,Data type data 2,...) { Code snippets for independent functions(Function body); return Calculation result of function; }
- Modifier: refers to the access permission of the function. public private is protected by default
- Function type: classification of functions, native functions, static functions, and synchronized functions
- Return value type: refers to the data type of the function calculation result. If the function has no return value, it is void
- Function name: the name of the function
- Parameter list: refers to the data (actual parameters) transferred from the outside to the function and received by these parameter variables (formal parameters)
- Function body: code fragment with independent function
- Return: the function ends only! If the function has a return value, return is followed by the return value; If there is no return value, return may not be written, but it exists (hidden in the last line)
According to the formal parameters and return values, functions are classified as follows:
- There are parameters and return values
- There are parameters but no return value
- No parameter has a return value
- No parameter, no return value
5.2 operation principle of function
The function is run based on the stack
Stack: it is a first in and last out container. What we call stack here refers to the stack memory space in the JVM.
Each function is called stack frame. The contents contained in the stack frame include function definition, parameter list, function execution content and code.
Each function to run is equivalent to the stack frame entering the stack memory - into the stack
If a function is about to end, move the stack frame from the top of the stack - out of the stack.
If there are multiple stack frames in the stack memory, the top stack frame is running, and the bottom stack frame is suspended until the stack frame is the top element of the stack.
For example, the main function goes to the stack first and starts to run line by line. If it runs to line N and calls another function A, the main function pauses running on line n, puts the stack frame of another function A on the stack, and then continues to run line by line until the content of function A is executed, function A is out of the stack, and the main function continues to execute downward from line n. and so on.
Examples are as follows:
public class Sample { public static void main(String[] args) { int a = 10; int b = 20; String s1 = "123"; String s2 = "456"; int c = test1(a,b); System.out.println(a); System.out.println(b); System.out.println(c); String s3 = test2(s1,s2); System.out.println(s1); System.out.println(s2); System.out.println(s3); } public static int test1(int a, int b) { a = 20; b = 30; return a + b; } public static String test2(String s1, String s2) { s1 = s1.replace("1","hehe"); s2 = s2.replace("4","heihei"); return s1 + s2; } }
import java.util.Scanner; public class Demo68{ public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); int number = input.nextInt(); System.out.println(isPalindrome(number)); } public static boolean isPalindrome(int number) { int revNumber = reverse(number); return revNumber == number; } public static int reverse(int num) { int result = 0; while(num != 0) { result = result * 10 + num % 10; num /= 10; } return result; } }
5.3 function overloading
Overloaded functions with the same name can be called overload ed functions
How to distinguish whether a function with the same name is an overloaded relationship? The premise must be the same name, which has nothing to do with the return value type (the return value type is only related to the calculation function of the function), has nothing to do with the permission, and has nothing to do with the name of the formal parameter! It is only related to the data type of formal parameters (quantity, arrangement and combination).
public static void show(int a ,float b ,char c){}
Which of the following are overloads of this function:
- int show(int x, float y, char z): the data type is int float char without overloading
- void show(float b,int a,char c): overloaded, in different order
- void show(int a,int b,int c): overloaded, in different order
- double show(): overloaded, with different parameters
Process for finding overloaded functions:
- See if there is an exact parameter definition matching, int int int
- See if there is a compatible parameter definition match. Int find double double or int double or double int
- If there are many compatible parameter definitions matching, the reference will be confirmed and the error will be reported. The reference is not clear
5.4 function recursion
The recursion of a function means that the function itself calls itself.
- Any problem that can be solved by iteration can be solved by recursion; The problem that recursion can solve is not necessarily iterative
- Relatively speaking, from the perspective of memory, if a function calls itself too much, it is bound to be unfriendly to memory and occupy too much memory
- Generally speaking, there is less code to write the same problem recursively than iteratively
When writing recursion, you must first determine the end condition of recursion - recursion boundary
public class Sample { public static void main(String[] args) { //show(); // infinite recursion test(10); } public static void test(int n) { System.out.println(n); if (n == 1) { return; } else { test(n - 1); } } public static void show() { System.out.println("Hello!"); show(); } }
Recursive implementation of 1 + 2 +... + 99 + 100
import java.util.Scanner; public class Sample { public static void main(String[] args) { System.out.println(f(100)); //System.out.println(f(10000000));//StackOverflowError int sum = 0; for (int i = 1; i <= 10000000; i++) { sum += i; } System.out.println(sum); } /* Find 1 + 2 ++ 99+100 Let function f (x) = 1 + 2 + 3 ++ x-3 + x-2 + x-1 + x f(3) = 1 + 2 + 3 f(2) = 1 + 2 f(3) = f(2) + 3 => 1 ,x = 1 f(x) = f(x-1) + x , x>1 Recursive implementation of Fibonacci sequence f(x) = f(x- 1) + x f(100) = f(99) + 100 1+2+3+...+99 + 100 f(99) = f(98) + 99 1+2+3+...+98 + 99 ..... f(4) = f(3) + 4 1+2+3 + 4 f(3) = f(2) + 3 1+2 + 3 f(2) = f(1) + 2 1 + 2 f(1) = 1 Recursive boundary */ public static int f(int x) { if (x == 1) { return 1; } else { return f(x - 1) + x; } } }
Recursive implementation of Fibonacci sequence
public class Sample { public static void main(String[] args) { /* 1 1 2 3 5 8 13 21 34 55 ... 1 x=1,x=2 f(x) = f(x-1) + f(x-2) x>2 f(5) f(4) f(3) f(3) f(2) f(2) f(1) f(2) f(1) */ //Recursive O(2^n) System.out.println(f(35)); //Iteration O(n) System.out.println(fibo_it(35)); } public static int fibo_it(int x) { if (x == 1 || x == 2) { return 1; } /* 1 1 2 3 c a b */ int a = 1; int b = 1; int c = 0; for (int i = 3; i <= x; i++) { c = a + b; a = b; b = c; } return c; } public static int f(int x) { if (x == 1 || x == 2) { return 1; }else { return f(x-1) + f(x-2); } } }
5.5 programming exercises
Hanoi Tower problem
public class Demo81 { public static void main(String[] args) { String x = "x"; String y = "y"; String z = "z"; hano(3,x,y,z); //The first three layers are from X - > Z //The first two layers are from X - > y } ///< param name = "begin" > column carrying the original disc < / param > ///< param name = "mid" > column for transit < / param > ///< param name = "end" > target column moved to < / param > public static void hano(int level,String begin,String mid,String end) { if (level == 1) { System.out.println(begin+"->"+end); } else { //Move the n-1 disks from top to bottom on the begin column to the mid column hano(level - 1,begin,end,mid); //Put the largest plate on top System.out.println(begin+"->"+end); //Move the n-1 plates on the mid column to the end column hano(level - 1,mid,begin,end); } } }
6, Array
6.1 concept and definition of array
Array is mainly used to solve the problem of calculation and storage of a large amount of data.
Definition: array is the simplest data structure provided by Java. It can be used to store an ordered set with a fixed number of elements and the same type.
Array in memory
Stack: memory mainly used to run functions
Heap: memory mainly used to store data objects
For each array, it is stored in heap memory, and each array is an object.
1. Array is essentially a series of storage spaces (variables) with continuous addresses and equal space size in heap memory. Each storage space is used to store data (basic, reference).
2. Array is stored in heap memory, which is called an array object, and the data stored in heap memory has the default initialization process. Therefore, at the beginning of array creation, the JVM initializes the zero value corresponding to the data type in each storage space.
2. The address of the array is continuous, so other elements can be accessed quickly through the formula: An=A1+(n-1)*d. therefore, it is faster to find elements for the array. Convert the real physical address of the element into the corresponding corner mark to obtain the element.
3. How to call an array? The address of the first element of the array in heap memory is stored through a variable.
4. Once the array is defined, its length is immutable and the content of storage space is variable.
5. So when we define an array, we either fix the length or directly enter the relevant elements.
How arrays are defined
//Create a one-dimensional array with a specified length and a specified data type. The name is the array name. Although no element is specified, it will have a default value data type[] Array name = new data type[length]; //Create a one-dimensional array with a specified element and a specified data type. The name is the array name. Although there are specified elements, there is still a default initialization step! data type[] Array name = new data type[]{Data 1,Data 2,...,data n}; data type[] Array name = {Data 1,Data 2,...,data n};
public class Sample { public static void main(String[] args) { int[] arr = new int[5]; System.out.println(arr[0]); //System.out.println(arr[5]); //ArrayIndexOutOfBoundsException arr[2] = 10; int[] arr2 = arr; System.out.println(arr2[2]); arr2 = null; //System.out.println(arr2[2]); //NullPointerException /* String s = null; s.length(); */ arr = null; } }
6.2 common array operations
Array traversal problem
public class Sample { public static void main(String[] args) { int[] arr = new int[]{1,2,3,4,5,6,7,8,9}; //String str str.length() - function //Int [] arr.length - attribute for (int i = 0; i < arr.length; i++) { arr[i] = arr[i] * 10; System.out.println(arr[i]); } //The specified elements can be modified in the process of traversal through corner mark traversal //foreach traversal mainly aims at some iteratable objects /* for (Data type (variable name: iteratable container){ } */ for (int num : arr) { //num -> arr[i] num = num / 10; System.out.println(num); } //This traversal method can only get elements and cannot modify elements for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
Array maximum value problem
public class Sample { public static void main(String[] args) { int[] arr = new int[]{3,6,8,2,9,4,5,1,7}; int min = arr[0]; int max = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] < min) { min = arr[i]; } if (arr[i] > max) { max = arr[i]; } } System.out.println(max); System.out.println(min); } }
Array expansion problem
public class Sample { public static void main(String[] args) { int[] arr = new int[]{1,2,3,4,5}; arr = add(arr,6); arr = add(arr,6); arr = add(arr,6); arr = add(arr,6); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } //Adds an element to the specified array arr public static int[] add(int[] arr, int element) { int[] newArr = new int[arr.length + 1]; for (int i = 0; i < arr.length; i++) { newArr[i] = arr[i]; } newArr[newArr.length - 1] = element; return newArr; } }
Select Sorting Algorithm
Idea: compare the first number with all the following numbers every time, find out the minimum value and put it in the first place. Move the first number to the second place, and compare the remaining numbers in a circular way to find the second smallest number, and so on.
public class Sample { //Select sort public static void main(String[] args) { int[] arr = {8,9,2,6,7,1,4,5,3}; for (int i = 0; i < arr.length - 1; i++) { //-1 n numbers without round n for (int j = i + 1; j < arr.length; j++) { if (arr[i] > arr[j]) { swap(arr,i,j); } } } print(arr); } //[1, 2, 3, 4, 5] public static void print(int[] arr) { System.out.print("["); for (int i = 0; i < arr.length;i++) { System.out.print(arr[i]); if (i == arr.length - 1) { System.out.println("]"); } else { System.out.print(", "); } } } public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
Bubble sort algorithm
Idea: each time the first number is compared with the following number, it will interact with the position if it is larger than the latter. On the contrary, it will not be exchanged. It will be compared in pairs, and the maximum value will appear to the last digit. The next cycle will be reduced once, because each cycle comparison will find the current maximum value, and so on.
public class Sample { //Bubble sorting public static void main(String[] args) { int[] arr = {8,9,2,6,7,1,4,5,3}; for (int i = 0; i <arr.length - 1; i++) {//-1 means n numbers, only n-1 rounds for (int j = 0; j < arr.length - 1 - i; j++) {//-1 avoid repeated comparisons (current maximum and previous maximum) Wheel maximum) if (arr[j] > arr[j + 1]) { swap(arr,j,j+1); } } } print(arr); } public static void print(int[] arr) { System.out.print("["); for (int i = 0; i < arr.length;i++) { System.out.print(arr[i]); if (i == arr.length - 1) { System.out.println("]"); } else { System.out.print(", "); } } } public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
Insertion sorting algorithm
Idea:
1. Compare from the second data of the array, that is, compare the second number with the previous one at the beginning. If the conditions are met (larger or smaller than the previous one, customized), let them exchange positions.
2. Then compare the third number with the second one. If it meets the requirements, it will be exchanged. However, we have to continue to compare here. For example, there are five numbers, 8, 15, 20, 45, 17 and 17, which are smaller than 45. They need to be exchanged, but 17 is also smaller than 20. When they do not need to be exchanged with 15, it means that they do not need to be compared with the data in front of 15. They certainly do not need to be exchanged, Because the previous data are orderly.
3. Repeat step 2 until all the data are arranged.
public class Sample { //Insert sort public static void main(String[] args) { int[] arr = {8,9,2,6,7,1,4,5,3}; for (int i = 1; i < arr.length; i++) { int e = arr[i]; int j = 0; for (j = i; j > 0 && arr[j - 1] > e; j--) { arr[j] = arr[j - 1]; } arr[j] = e; } print(arr); } public static void print(int[] arr) { System.out.print("["); for (int i = 0; i < arr.length;i++) { System.out.print(arr[i]); if (i == arr.length - 1) { System.out.println("]"); } else { System.out.print(", "); } } } }
Binary search algorithm
Idea: in the ordered array, find the minimum value, maximum value and intermediate value every time, compare the size of the intermediate value with the current value. If it is greater than, redefine the maximum value, minimum value and intermediate value on the right of the ordered array. If it is less than, repeat the above steps (definition and left), and return the subscript when it is found, When the subscript of the minimum value is greater than the subscript of the maximum value, it indicates that it is not found and returns - 1
public class Sample { //Binary search public static void main(String[] args) { int[] arr = {1,2,3,4,5,6,7,8,9}; int min = 0; int max = arr.length - 1; int mid = (min + max) / 2; int key = 10; while (arr[mid] != key) { if (key < arr[mid]) { max = mid - 1; } if (arr[mid] < key) { min = mid + 1; } if (min > max) { mid = -1; break; } mid = (min + max) / 2; } System.out.println(mid); } }
Count sort:
public class Sample { //Count sort public static void main(String[] args) { int[] arr = {-2,9,-1,12,8,-3,6,7,4,5,2,1,0,8,6,7,4,-3,-2,-1,-1,7}; int min = arr[0]; int max = arr[0]; //O(n) for (int i = 1; i < arr.length; i++) { if (arr[i] < min) { min = arr[i]; } if (arr[i] > max) { max = arr[i]; } } int[] temp = new int[max - min + 1]; //Correspondence index = number - min number = index + min //O(n) for (int i = 0; i < arr.length; i++) { temp[arr[i] - min]++; } //temp[index] indicates the number of times the number corresponding to index appears int k = 0; //O(n) for (int index = 0; index < temp.length; index++) { while (temp[index] != 0) { arr[k] = index + min; k++; temp[index]--; } } print(arr); } public static void print(int[] arr) { System.out.print("["); for (int i = 0; i < arr.length;i++) { System.out.print(arr[i]); if (i == arr.length - 1) { System.out.println("]"); } else { System.out.print(", "); } } } }
Cardinality sorting:
import java.util.LinkedList; public class Sample { //Cardinality sort public static void main(String[] args) { int[] arr = {102,203,321,13,12,78,96,34,37,28,6,8,5,6}; //1. First find the maximum value to determine the number of rounds int max = arr[0]; for (int i = 0; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } int radex = (max + "").length(); //2. Create ten buckets, each of which is a LinkedList LinkedList<Integer>[] queues = new LinkedList[10]; for (int i = 0; i < queues.length; i++) { queues[i] = new LinkedList<Integer>(); } //3. Digital classification and regularization //r=0 bits r=1 tens r=2 hundreds for (int r = 0; r < radex; r++) { //First classify according to r for (int i = 0; i < arr.length; i++) { int index = getIndex(arr[i],r);//Get the r bit of the number and return the corner mark 0 ~ 9 of the bucket to which the number is going queues[index].offer(arr[i]); } //And then rearrange it into the arr int k = 0; for (int index = 0; index < queues.length; index++) { while(!queues[index].isEmpty()) { arr[k++] = queues[index].poll(); } } } print(arr); } public static int getIndex(int number, int r) { //123 r=0 //123 r=1 //123 r=2 int index = 0; for (int i = 0; i <= r; i++) { index = number % 10; number /= 10; } return index; } public static void print(int[] arr) { System.out.print("["); for (int i = 0; i < arr.length;i++) { System.out.print(arr[i]); if (i == arr.length - 1) { System.out.println("]"); } else { System.out.print(", "); } } } }
6.3 two dimensional array
A two-dimensional array is a table in the form of expression. When operating the table, it is operated by rows and columns
The so-called two-dimensional array is essentially a one-dimensional array, but the elements in the one-dimensional array are another one-dimensional array
Definition of two-dimensional array:
public class Sample { public static void main(String[] args) { //Data type [] [] matrix name = new data type [row][col]; int[][] matrix = new int[3][2]; /* Data type [] [] matrix name = new data type [] []{ {...}, {...}, {...} }; Data type [] [] matrix name ={ {...}, {...}, {...} }; */ int[][] matrix2 = { {1,2,3}, {4,5,6}, {7,8,9} }; for (int i = 0; i < matrix2.length; i++) { for (int j = 0; j < matrix2[i].length; j++) { System.out.print(matrix2[i][j] + " "); } System.out.println(); } int[][] matrix3 = { {1}, {1,2,3}, {1,2,3,4}, {7,6,5,4,3,2,1} }; for (int i = 0; i < matrix3.length; i++) { for (int j = 0; j < matrix3[i].length; j++) { System.out.print(matrix3[i][j] + " "); } System.out.println(); } } }
Case 1
Enter the coordinates of 8 points, and then calculate which of these points is the closest?
Idea: define a two-dimensional array to accept the coordinates of eight points input by the user, and judge the distance between the two coordinates in a cycle, so as to obtain the shortest distance between the two points.
import java.util.Scanner; public class Sample { public static void main(String[] args) { Scanner input = new Scanner(System.in); //Define a two-dimensional array with 8 rows and 2 columns double[][] points = new double[8][2]; //1. Obtain the input point coordinates for (int i = 0; i < points.length; i++) { System.out.print("Please enter page" + (i + 1) + "Point coordinates:"); points[i][0] = input.nextDouble(); points[i][1] = input.nextDouble(); } //The default shortest distance is point 0 and point 1 double shortestDistance = getDistance(points,0,1); int p1 = 0; int p2 = 1; for (int i = 0; i < points.length - 1; i++) { for (int j = i + 1; j < points.length; j++) { double distance = getDistance(points,i,j); //Compare and judge the shortest distance, and obtain the subscript if it is less than if (distance < shortestDistance) { shortestDistance = distance; p1 = i; p2 = j; } } } System.out.printf("(%.1f,%.1f)and(%.1f,%.1f)The distance is the shortest%.1f",points[p1] [0],points[p1][1],points[p2][0],points[p2][1],shortestDistance); } public static double getDistance(double[][] m , int p1 , int p2) { //Calculate the distance between two points with function return Math.hypot(m[p1][0] - m[p2][0] , m[p1][1] - m[p2][1]); } }
6.4 programming exercises
Idea: count sorting idea, count the corresponding numbers according to the subscript, and finally output.
import java.util.Scanner; public class Demo82{ public static void main(String[] args) { System.out.print("Enter the number between 1 and 100:"); Scanner input = new Scanner(System.in); //The array holds the number entered by the user. 0 indicates the end of input int[] array = new int[101]; while(true) { int num = input.nextInt(); if(num == 0){ break; } //Add 1 to the subscript of the corresponding array of input numbers array[num]++; } //Circularly output the number of times the corner mark appears in the array. No matter the number is 0, 1 time is output, otherwise times is output for(int i=0;i<array.length;i++){ if(array[i] != 0){ if(array[i] == 1){ System.out.println(i+" occurs "+array[i]+" time"); }else{ System.out.println(i+" occurs "+array[i]+" times"); } } } } }
Idea:
Idea 1: dynamically expand the array, define an array with a length of 0, and cycle 10 times from 0. Each time, judge whether the array contains the array entered by the user, and skip if it contains it. Otherwise, expand the defined array, and expand a number every time.
Idea 2: for a fixed array length, mark the valid data, define the array length as 10, and define a variable size to mark the number of valid numbers and subscripts.
import java.util.*; public class Demo83{ public static void main(String[] args) { //Idea 1: dynamic expansion array // int[] array = new int[0]; // System.out.print("Enter ten numbers:"); // Scanner input = new Scanner(System.in); // for(int i=0;i<10; i++) { // int num = input.nextInt(); // if(!container(array,num)){ // array = add(array,num); // } // } // System.out.println(Arrays.toString(array)); //Idea 2: fix the length of the array and use markers to represent the data int[] array = new int[10]; //That is, it represents the number of significant digits and the angle of the current array int size = 0; System.out.print("Enter ten numbers:"); Scanner input = new Scanner(System.in); for(int i=0;i<10; i++) { int num = input.nextInt(); if(!container(array,num,size)){ array[size++] = num; } } System.out.println(toString(array,size)); } //Customize arrays toString(); method public static String toString(int [] arr,int size){ String s="["; for(int i=0;i<size; i++) { if(arr[i] !=0){ if(i == size-1){ s += arr[i]+"]"; }else{ s += arr[i]+","; } } } return s; } //Overload method (idea 2) public static boolean container(int[] arr,int num,int size){ for(int i=0;i<size; i++) { if(arr[i] == num){ return true; } } return false; } //Dynamically expand the array, one number at a time public static int[] add(int[] arr,int num){ int[] newArr = new int[arr.length+1]; for(int i=0;i<arr.length; i++) { newArr[i] = arr[i]; } newArr[arr.length] = num; return newArr; } //Loop through whether the current number of the array is already in the array public static boolean container(int[] arr,int num){ for(int i=0;i<arr.length; i++) { if(arr[i] == num){ return true; } } return false; } }
Idea: get the minimum value in the array, traverse in reverse order from the changed value, find a number that can divide all the numbers in the array, find it, and then return and output the number.
import java.util.*; public class Demo85{ public static void main(String[] args) { System.out.println(gcd(35,40,20,55)); System.out.println(gcd(28,16)); } //Method to return the maximum common divisor public static int gcd(int ... numbers) { int min = getMin(numbers); //Each time we traverse from the minimum value, we loop to judge whether the number can divide each number in the array, and then return the output for(int i=min; i>=1; i--) { boolean flag = true; for(int j=0; j<numbers.length; j++){ if(numbers[j] % i != 0){ flag = false; break; } } if(flag) { return i; } } return 1; } //Gets the minimum value in the input array public static int getMin(int[] array) { int min = array[0]; for(int i=1; i<array.length;i++) { if(array[i] < min){ min = array[i]; } } return min; } }
Idea: use random numbers to simulate the path of small balls. 1 represents R and 0 represents L. generate the number of paths of input small balls each time, and count the number of R. judge the number of small balls falling into the slot according to the number of R. add 1 to the number of corresponding slots and print the array of slots.
import java.util.*; public class Demo88{ public static void main(String[] args) { Scanner input = new Scanner(System.in); //Random number 1 represents R, and 0 represents L Random random = new Random(); System.out.print("Please enter the number of balls:"); int balls = input.nextInt(); System.out.print("Please enter the number of slots:"); int slots = input.nextInt(); //Define an array of slots, and the saved value is the number of small balls int[] temp = new int[slots]; //Define the number of paths and the path of each small ball randomly generated String[] paths = new String[balls]; //The number of cycles is the number of small balls for(int i=0; i<balls; i++) { //The specific path of each ball String path = ""; //Number of occurrences of R in the path int Rcount = 0; for(int j=0; j<slots-1; j++){ if(random.nextInt(2) == 0) { path += "L"; }else{ path += "R"; Rcount++; } } paths[i] = path; System.out.println(path); temp[Rcount]++; } System.out.println(Arrays.toString(temp)); } }
Idea: refer to code comments
import java.util.*; public class Demo90{ public static void main(String[] args){ //Get input data System.out.print("Please enter the number of numbers:"); Scanner input = new Scanner(System.in); int num = input.nextInt(); System.out.print("Please enter"+num+"Number:"); int[] arr = new int[num]; //Define a one-dimensional array with a number length of num to save the numbers entered by the user for(int i=0; i<arr.length; i++){ arr[i] = input.nextInt(); } //Method to determine whether there are four consecutive numbers in the array isConsecutiveFour(arr); } public static void isConsecutiveFour(int[] arr) { //Loop to judge the consecutive equal numbers in the array, and the equal counter will increase by one. When it reaches 4, it will output true to end the program operation. Otherwise, start the loop again from J for(int i=0; i < arr.length;) { //count is 1, and one is removed in advance for judgment int count = 1,j=0; for(j=i+1; j < arr.length; j++) { if(arr[i] == arr[j]){ count++; }else { break; } } if(count >= 4){ System.out.println("true"); return; }else{ i=j; } } System.out.println("false"); } }
Idea: compare the values in the two arrays as shown in the figure above, but each comparison is to judge whether one of the subscripts of the two arrays has crossed the boundary. For those that have crossed the boundary, just splice the numbers behind the array without crossing the boundary, and compare the two arrays without crossing the boundary.
import java.util.*; public class Demo91{ public static void main(String[] args) { int[] list1 = {1,3,5,7,9,50,90}; int[] list2 = {2,4,6,8,10}; //Call the method to get the final array after splicing two sorts int[] list3 = merge(list1,list2); System.out.println(Arrays.toString(list3)); } public static int[] merge(int[] arr1,int[] arr2) { //The length of the returned array is the sum of the lengths of the two arrays int[] arr3 = new int[arr1.length + arr2.length]; //Subscripts start at 0 int p1=0,p2=0,p3=0; //First judge whether the two subscripts are out of bounds (the length of the array) while(p1 < arr1.length || p2 < arr2.length){ //Each time, judge whether one of the two arrays has a subscript that is out of bounds (if you directly judge the size of the two values first, the subscript will be out of bounds) if(p1 >= arr1.length && p2 < arr2.length){ arr3[p3++] = arr2[p2++]; }else if(p2 >= arr2.length && p1 < arr1.length){ arr3[p3++] = arr1[p1++]; }else if(arr1[p1] > arr2[p2]) { arr3[p3++] = arr2[p2++]; }else{ arr3[p3++] = arr1[p1++]; } } return arr3; } }
Idea: see code comments
import java.util.*; public class Demo92{ public static void main(String[] args) { //Define a string array for the word thesaurus to guess String[] words = {"apple","banana","python","computer"}; Scanner input = new Scanner(System.in); Random random = new Random(); while(true){ //Get a word randomly from the thesaurus String word = words[random.nextInt(words.length)]; //Define a state array of words. true represents the words displayed in plaintext and false represents the words displayed in ciphertext boolean[] status = new boolean[word.length()]; //Count the number of guesses wrong int count = 0; while(!isOver(status)){ //Each time, the characters to be displayed in ciphertext or plaintext are displayed according to the status array String password = getPassWord(word,status); System.out.print("Enter a letter in word "+password+" > "); //Gets the word entered by the user String letter = input.nextLine(); //Determine whether the letter is in the word if(word.contains(letter)){ //When changing the status array, if the status is already true, the following prompt will be output if(!changeStatues(word,letter,status)){ System.out.println("\t" + letter + " is alreay in the word"); } }else{ //Record the number of input errors without the input characters and print the information System.out.println("\t"+letter+" is not in the word."); count++; } } System.out.println("The word is " + word + ". You missed " + count); //Cycle game System.out.print("Do you want again?(y/n):"); String choice = input.nextLine(); if(choice.equals("n")){ break; } } } public static boolean changeStatues(String word,String letter, boolean[] status){ //To change the value in the status array, first obtain the subscript of the same character, and then judge whether the subscript in the status array is true. If it is true, return false (indicating that the character is guessed to eliminate repeated guessing), otherwise return true char ch = letter.charAt(0); for(int i=0; i<word.length(); i++) { if(word.charAt(i) == ch){ if(status[i]){ return false; }else{ status[i] = true; } } } return true; } //Judge whether to continue. If the status array is all true, the game is over public static boolean isOver(boolean[] status){ for(int i=0;i<status.length;i++){ if(!status[i]){ return false; } } return true; } public static String getPassWord(String word,boolean[] status) { //Judge that the status array is true, the corresponding subscript letter is displayed in clear text, and * ciphertext is displayed in false String password = ""; for(int i=0; i<status.length; i++){ if(status[i]){ password += word.charAt(i); }else { password += "*"; } } return password; } }
Idea: (make Gobang directly here)
import java.util.Scanner; public class Demo101 { //1. Define 15 * 15 a chessboard public static String[][] baord = new String[15][15]; //The player's round count (also the number of pieces) even indicates black chess, and odd indicates white chess public static int player = 0; //Black (O) and white (X) public static final String BLACK_CHESS = "O"; public static final String WHITE_CHESS = "X"; public static Scanner input = new Scanner(System.in); public static void main(String[] args) { //2. Initialize chessboard and print chessboard initBoard(); printBoard(); //3. Start playing chess startGame(); } public static void startGame() { //As long as there are no five pieces connected on the chessboard, continue to play chess while(!isGameOver()){ if(player % 2 ==0) { //Black chess System.out.println(">>>Please play black chess"); playChess(BLACK_CHESS); }else{ //White chess System.out.println(">>>Please play chess with Bai Fang"); playChess(WHITE_CHESS); } player++; } //If the number of chess pieces is equal to the number of chessboards, it is a draw if(player == 15 * 15){ System.out.println(">>>Draw, the game is over!"); }else { //Judge which chess piece wins according to the number of chess pieces (- 1 means to add 1 after the cycle, all of which should be subtracted here) if((player-1) % 2 == 0) { System.out.println(">>>Black chess wins, the game is over!"); }else { System.out.println(">>>White chess wins, the game is over!"); } } } //Judge whether there are 5 pieces connected on the chessboard (whether the game is over) public static boolean isGameOver() { for(int row=0; row<baord.length;row++) { for(int col=0;col<baord[row].length;col++) { if(!baord[row][col].equals("+")){ //Judge the chess piece to the right (11 is the boundary value to the right) if(col < 11){ boolean flag = true; for(int c=col + 1; c<=col+4; c++){ if(!baord[row][col].equals(baord[row][c])){ flag = false; break; } } if(flag){ return true; } } //Chess piece downward judgment if(row < 11){ boolean flag = true; for(int r=row + 1; r<=row+4; r++){ if(!baord[row][col].equals(baord[r][col])){ flag = false; break; } } if(flag){ return true; } } //The chess piece is judged up to the right if(row > 3 && col < 11){ boolean flag = true; for(int r=row - 1,c = col + 1; c <= col+4;r--,c++){ if(!baord[row][col].equals(baord[r][c])){ flag = false; break; } } if(flag){ return true; } } //The chess piece goes down to the right to judge if(row < 11 && col < 11){ boolean flag = true; for(int r=row + 1,c = col + 1; c <= col+4;r++,c++){ if(!baord[row][col].equals(baord[r][c])){ flag = false; break; } } if(flag){ return true; } } } } } return false; } //Chess playing method public static void playChess(String chess) { System.out.print("Please enter the coordinates of the chess piece:"); int x = input.nextInt() - 1; int y = input.nextInt() - 1; if(!baord[y][x].equals("+")) { //Judge whether there are chessmen there, and if so, the number of chessmen played -- return to the last time System.out.println("There are already chess pieces here. Please try again!"); //--Back to the previous step player--; return; } //The corresponding pieces under the chessboard and reprint the chessboard baord[y][x] = chess; printBoard(); } //Format and print the chessboard and the corresponding serial number on the top and left of the chessboard public static void printBoard(){ System.out.print(" "); for(int i=1; i<=baord[0].length; i++){ System.out.printf("%-3d",i); } System.out.println(); for(int i=0;i<baord.length;i++){ System.out.printf("%2d ", i + 1); for(int j=0;j<baord[i].length;j++) { System.out.print(baord[i][j]+" "); } System.out.println(); } } //Initialize chessboard public static void initBoard(){ //Cycle the chessboard to assign (+) to the chessboard for(int i=0;i<baord.length;i++){ for(int j=0;j<baord[i].length;j++) { baord[i][j]="+"; } } } }
Eight queens problem
Idea: simply understand that recursion is a loop nested loop. After the loop is completed, it returns to the previous one and does not end until the execution of the outermost loop at the top is completed. If the whole loop is output, the result can be output according to specific conditions.
public class NQueen{ //Queen N public static int N = 8; //checkerboard public static int[][] board = new int[N][N]; //There are several solutions to statistics public static int count = 0; public static void main(String[] args) { nqueen(0); } public static void nqueen(int row) { //If the line is increased to equal to N, the combination is a solution, which can be printed out directly if(row == N){ count++; System.out.printf("This is the second%d Two solutions:\n",count); for(int i=0; i<board.length; i++){ for(int j=0; j<board[i].length; j++){ System.out.print(board[i][j]+" "); } System.out.println(); } }else{ //Otherwise, start with each cell in the first row for(int col=0; col<N; col++) { //If it can be empty, clear the row first and put the queen on the corresponding coordinates if(!isDangerous(row,col)){ for(int c=0; c<N; c++){ board[row][c] = 0; } board[row][col] = 1; //Recursion to the next line (nesting of loops) nqueen(row+1); } } } } //Judge whether the current blank can be placed public static boolean isDangerous(int row,int col) { //Upward judgment, line decreasing for (int r = row - 1;r >= 0; r--) { if (board[r][col] == 1) { return true; } } //Judging from the left, the ranks decrease for (int r = row - 1,c = col - 1; r >= 0 && c >= 0;r--,c--) { if (board[r][c] == 1) { return true; } } //Judge to the right and up, the row decreases and the column increases for (int r = row - 1,c = col + 1; r >= 0 && c < N; r--,c++) { if (board[r][c] == 1) { return true; } } //You can return false return false; } }
6.4 LeetCode question
Idea: reverse the loop to judge whether the carry is generated. If the carry is generated, continue the loop. If there is no carry, exit directly. If there is still carry after the loop, expand the capacity of the array and assign the first value to 1.
class Solution { public int[] plusOne(int[] digits) { //Carry character. The default is 1, which means plus 1 int carry = 1; //Reverse cycle for(int i=digits.length-1; i>=0; i--) { //Add one to the last number, take the remainder and assign value, divide by 10 and take the carry character int num = digits[i] + 1; digits[i] = num % 10; carry = num / 10; //Exit the program with a carry of 0 if(carry == 0){ break; } } //When there is carry after the loop, expand the capacity of the array if(carry == 1){ int[] arr = new int[digits.length+1]; arr[0] = 1; return arr; } return digits; } }
Expand the addition of two arrays
import java.util.*; public class LeetCode66{ public static void main(String[] args) { int[] arr1 = {9,9,9}; int[] arr2 = {9,9,9,9,9}; System.out.println(Arrays.toString(plus(arr1,arr2))); } public static int[] plus(int[] digits1,int[] digits2) { //Expand the capacity of the two arrays to the same length, and expand the smaller one if(digits1.length < digits2.length) { digits1 = kuorong(digits1,digits2.length); }else if(digits1.length > digits2.length) { digits2 = kuorong(digits2,digits1.length); } //Carry character int carry = 0; //The array is added from the back for(int i=digits1.length-1; i>=0; i--){ //Add every two numbers in the two arrays and add the carry character. The first time is 0. After each addition, re assign the carry character int num = digits1[i] + digits2[i] + carry; //Judge whether the two numbers currently added generate carry carry = num / 10; //Assign the addition result to array 1 digits1[i] = num % 10; } //If the carry character is 1 after the loop is completed, it means that the capacity of the array should be expanded to generate carry if(carry == 1){ //Define a new array, the first bit is 1, the following bits are assigned by traversing digits1, and finally return digits3 int[] digits3 = new int[digits1.length + 1]; digits3[0] = 1; for(int i=0;i<digits1.length;i++){ digits3[i+1] = digits1[i]; } return digits3; } //Return to digits1 if the carry is not generated after the loop return digits1; } //Array expansion num is the length to be expanded public static int[] kuorong(int[] arr, int num) { int[] newArr = new int[num]; //Defines that both subscripts are decremented from the last bit of the array int i = arr.length - 1,k = newArr.length - 1; //Assign a value to the new array from the back to the front, and the lower corner is 0 while(i >= 0){ newArr[k--] = arr[i--]; } return newArr; } }
Idea: (see code comments)
public class LeetCode283{ public void moveZeroes(int[] nums) { //Train of thought 1: Select Sorting train of thought // for(int i=0; i<nums.length - 1; i++) { // for(int j=i+1; j<nums.length; j++){ // //If the left is 0 and the right is not 0, it will be exchanged // if(nums[i] == 0 && nums[j] != 0){ // int temp = nums[i]; // nums[i] = nums[j]; // nums[j] = temp; // break; // } // } // } //Idea 2: insert sorting idea // for(int i=1; i<nums.length; i++) { // //If it is 0, skip this cycle // if(nums[i] == 0){ // continue; // } // //Swap positions as long as j-1 is 0 // for(j=i; j>0 && nums[j-1] == 0; j--){ // int temp = nums[i]; // nums[j] = nums[j-1]; // nums[j-1] = temp; // } // } //Train of thought 3: the double pointer method k has been stuck with the first 0 //End the program directly when the array is empty if(nums == null){ return; } //Define a k that always points to the first 0 in the array int k = 0; for(int i=0; i<nums.length; i++){ //If the current element is not 0, exchange the values corresponding to the i and k subscripts (if it is not 0, you can interact with yourself). If it is 0, you can go directly to the next number that is not 0 if(nums[i] != 0){ int temp = nums[i]; nums[i] = nums[k]; nums[k] = temp; k++; } } } }
Idea: sort the array and take out the number at n/2 position after sorting, that is, most elements of the array.
Train of thought 2, positive and negative cancel each other.
class Solution { public int majorityElement(int[] nums) { //Idea 1: insert sorting. After sorting, the middle position must be mode /* for (int i = 0; i < nums.length; i++) { int e = nums[i]; int j = 0; for (j = i; j > 0 && nums[j - 1] > e; j--) { nums[j] = nums[j - 1]; } nums[j] = e; } return nums[nums.length / 2]; */ //Train of thought 2: eliminate positive and negative //The first number in the array appears by default, and the number of occurrences is 1 int num = nums[0]; int count = 1; //Cycle judgment from the second number in the array. If it is equal to the number of occurrences, increase the number by 1 //It is not equal to subtracting 1 from the number of times to offset a number. If the number of times is less than 0, it indicates that another number appears. Assign another number and assign the number of times to 1 for(int i=1; i<nums.length; i++){ if(nums[i] == num){ count++; }else{ if(count > 0){ count--; }else{ num = nums[i]; count = 1; } } } return num; } }
Idea: define the left and right pointers, judge the left and right parity, replace or move the pointers according to the situation.
class Solution { public int[] sortArrayByParity(int[] A) { int l = 0; int r = A.length - 1; while(l < r){ //Left odd right even if(A[l] % 2 == 1 && A[r] % 2 == 0) { int temp = A[l]; A[l] = A[r]; A[r] = temp; //Left even right odd }else if(A[l] % 2 == 0 && A[r] % 2 == 1){ l++; r--; //Left odd right odd }else if(A[l] % 2 == 1 && A[r] % 2 == 1){ r--; //Right couple right couple }else{ l++; } } return A; } }
Idea: sum the array, divide the sum by three, and divide it into three groups. Loop the array. Subtract the value of each array with the number of sum and divide by three. If the number of sum and divide by three is reduced to 0, it will be a group. Count the group, and re assign the number of sum and divide by three. Continue the loop judgment and return to judge whether the group count is 3.
class Solution { public boolean canThreePartsEqualSum(int[] arr) { int sum = 0; //Summation array for(int i=0; i < arr.length; i++){ sum += arr[i]; } //The sum is divided into three parts int key = sum / 3; //Group counter int group = 0; for(int i=0; i < arr.length; i++){ key -= arr[i]; //If the key is 0, it is a group, and the key is assigned if(key == 0){ group++; key = sum / 3; } } //Returns the result. If the sum is 0 and the number of groups is greater than 3, you can freely combine them into three groups and return true return group == 3 || sum == 0 && group >=3; } }
Idea: define the left and right pointers, calculate the sum of the left and right with the sum of the array, and judge whether the sum of the left and right is equal. If it is equal, it will return to the corner mark, end the operation of the program, and return - 1 when there is no result after the cycle.
class Solution { public int pivotIndex(int[] nums) { //Sum arrays int sum = 0; for(int i=0; i<nums.length; i++) { sum += nums[i]; } //Defines the sum of the left and right sides of the array int leftSum=0,rightSum=0; for(int i=0; i<nums.length; i++){ if(i == 0){ leftSum = 0; }else{ //Sum and accumulate the left side of the array leftSum += nums[i-1]; } //Sum the right of the array, subtract the sum on the left from the sum, and subtract the value corresponding to the current subscript rightSum = sum - leftSum - nums[i]; //If the left and right sides are equal, the program ends and the subscript returns if(rightSum == leftSum) { return i; } } return -1; } }
Idea: sliding window mechanism (see code)
class Solution { public int minSubArrayLen(int s, int[] nums) { int len = 0, i = 0, sum = 0; for(int j=0; j<nums.length; j++){ //Total sum sum += nums[j]; //If the total number is greater than s, judge whether the length is less than len first, and re assign the value to len if it is less than, otherwise narrow the window on the left //A value pops up on the left, and the corresponding total number will pop up. If the sum is smaller than s, expand the window on the right, add a value on the right, add one to the total number, and so on while(sum >= s) { len = len == 0 ? j-i+1 : Math.min(len,(j-i+1)); sum -= nums[i++]; } } return len; } }
more: The second part is object-oriented,Part III set,Part IV file flow,Part V multithreading,Part VI network programming