Shortcut key
ctrl+c copy (not available in cmd)
ctrl+v paste
ctrl+x cut
ctrl+a select all s
ctrl+d copies the current line to the next line
alt+f4 close window
alt+insert constructs with and without parameters
ctrl+z undo
ctrl+s save
Shift + delete permanently delete
win+r command line
ctrl+shift+esc Task Manager
ctrl+h inheritance tree
dos command
Switch drive letter
Drive letter +:
D:
Show file directory
dir
(div is part of the interval in html)
Cross drive letter directory display
cd (change directory) [cd can only enter the lower level directory directly or return to the upper level through cd...]
cd \d D:
Clear screen
cls(clear screen)
Exit terminal
exit
View PC ip
ipconfig
Open app
notepad extension
ping website ip
ping www.baidu.com
Create directory (folder)
md(make diretory)
md + + file name
create a file
md>a.txt
delete
md>del a.txt
rd
del is used to delete files; rd is used to delete folders
JDK
JRE
JVM
The first JAVA program
1. Create a file
2. Change the suffix of the document to java
3
input
public class Hello{ public static void main(String[] args){ System.out.print("Hello,world!"); } }
Compiling operation of java program in cmd
Add cmd before the detailed address of the file to open the manager
Compilation instruction: javac + space + file name (remember to add suffix)
After compilation, a class file (compiled file) will appear
Run java file: java + space + file name of the program to be run (there is no suffix at this time, because this operation must be a compiled file)
Java program running mechanism
Java annotation
1: Single line note//
2: Multiline comment/**/
3: Document notes/**
Java data type
Strongly typed language
All variables must be strictly defined before use
Weakly typed language
~
Basic data type
value type
1 integer type
int 4
long 8
short 2
byte 1
2 floating point type
float 4
double 8
3 character type
char 2
4. Boolean type 1
true
false
String a="Hello world"; int num=10; System.out.println(a); System.out.println(num); //Eight basic data types //plastic int num1=10; short num2=20; byte num3=127; long num4=50L; //The long shape is usually marked with L //float float num5=10.1F; //float shape should also be marked with F double num6=20.1; //Character shape char name='leaf'; //Single character //boolean value //boolean flag=true;
Reference data type
class
Interface
array
What are bytes
Relationship between byte, word, bit and byte
word
byte
bit
Word length refers to the length of a word
1 byte = 8 bits (1 byte = 8bit)
1 word = 2 bytes (1 word = 2 bytes)
The word length of a byte is 8
The length of a word is 16
BPS is short for bits per second. Generally, the transmission rate of modem and network communication is in bps. Such as 56Kbps, 100.0Mbps, etc.
Bps is short for Byte per second. Computers generally display speed in Bps. For example, 1Mbps is about the same as 128 KBps.
Bit is the smallest unit of computer memory. In binary computer system, each bit can represent a digital signal of 0 or 1.
Byte a byte consists of 8 bits, which can represent a character (AZ), a number (09), or a symbol (,.?!% &± * /), which is the basic unit of memory for storing data. Up to two Bytes are required for each Chinese character. When the memory capacity is too large, the byte unit is not enough, so the kilobyte unit KB appears. The following is the correlation between memory calculation units:
1 Byte = 8 Bits
1 KB = 1024 Bytes
1 MB = 1024 KB
1 GB = 1024 MB
usb2.0 standard interface transmission rate. Many people misunderstand "480mbps" as 480m / s. In fact, this is wrong. In fact, "480mbps" should be "480 megabits / second" or "480 megabits / second", which is equal to "60 megabytes / second". You see the gap.
This starts with bit and byte: bit and byte are both translated as "bit", which are data measurement units, bit = "bit" or "bit".
Byte = byte, i.e. 1byte=8bits. The conversion between the two is 1:8.
Mbps = Mega bits per second is the rate unit, so the correct way to say it is USB2 The transmission speed of 0 is 480 megabits per second, or 480mbps.
MB = Mega bytes is the unit of quantity, 1mb/s (megabytes / second) = 8mbps (megabits / second).
The hard disk capacity we mentioned is 40gb, 80gb and 100gb. Here b refers to byte, which is "byte".
1 kb = 1024 bytes =2^10 bytes
1 mb = 1024 kb = 2^20 bytes
1 gb = 1024 mb = 2^30 bytes
For example, the so-called 56kb modem in the past converts 56kbps divided by 8, which is 7kbyte, so the speed of downloading files from the Internet and storing them on the hard disk is 7kbyte per second.
In other words, b related to transmission speed generally refers to bit.
b related to capacity generally refers to byte.
One last thing: USB2 The transmission rate of 0 480mbps = 60MB / S is only a theoretical value. It is also restricted by the system environment (cpu, hard disk and memory). The actual speed of reading, fetching and writing to the hard disk is about 11 ~ 16mb/s. But it's also better than USB 1 12mbps(1.5m/s) of 1 is nearly 10 times faster
Reprinted from https://blog.csdn.net/wanlixingzhe/article/details/7107923/
Knowledge expansion
public class Demo03 { public static void main(String[] args) { //Integer extension //Binary 0b decimal octal 0 hex 0x int i=10; int i2=010;//Octal 0 int i3=0x10;//Hex 0x 0-9 A-F 16 System.out.println(i); System.out.println(i2); System.out.println(i3); //===================================================================== System.out.println("======================"); //Floating point extension //How to express banking business? //BigDecimal (mathematical tools) //===================================================================== //float finite discrete rounding error is approximately close to but not equal to //double //It is best to avoid using floating point numbers for shape comparison //It is best to avoid using floating point numbers for shape comparison //It is best to avoid using floating point numbers for shape comparison float f=0.1f; double d=1.0/10; System.out.println(f==d);//false float d1=2313313131313131332f; float d2=d1+1; System.out.println(d1==d2);//true //=================================== System.out.println("======================"); //Character extension char c1='A'; char c2='in'; System.out.println(c1); System.out.println((int)c1);//Force conversion System.out.println(c2); System.out.println((int)c2);//Force conversion //All characters are numbers in nature //Encoding Unicode table: (97 = a, 65 = a) 2 bytes 0-65536 //U0000 UFFFF char c3 ='\u0062'; System.out.println(c3);//b //Escape character // \Tabbed \ nline break /* java Escape character (Collection) There are four simple escape characters in JAVA: 1.Octal escape sequence: \ + 1 to 3 5 digits; Range '\ 000' ~ '\ 377' \0: Null character 2.Unicode Four hexadecimal characters: \ u; 0~65535 \u0000: Null character 3.Special characters: only 3 \": Double quotation mark \': Single quotation mark \\: Backslash 4.Control characters: 5 \' single quote \\ Backslash character \r enter \n Line feed \f Paper feed \t Horizontal skip \b Backspace Escape of dot:. = = > u002E Escape of dollar sign: $= = > u0024 Escape of power sign: ^ = = > u005e Escape of left brace: {= = > u007b Escape of left square bracket: [= = > u005b Escape of left parenthesis: (= = > u0028) Escape of vertical line: | = > u007c Escape of right parenthesis:) = = > u0029 Escape of asterisk: * = = > u002a Escape of plus sign: + = = > u002b Escape of question mark:? = = > u003F Escape of backslash: = = > u005c */ System.out.println("Hello\tworld"); System.out.println("Hello\nworld"); System.out.println("============================"); String sa = new String(original:"hello world"); String sb = new String(original:"Hello world") System.out.println(sa==sb); String sc = "hello world"; String sd = "hello world"; System.out.println(sc==sd); //Object from memory analysis //boolean value extension boolean flag = true; if(flag==true){}//Novice if(flag){}//an old hand //Less is more! } }
Type conversion
Because Java is a strongly typed language, type conversion is required for some operations
Low ------------------------------------------------------------- high
byte,short,char,int,long,float,double
In the operation, different types of data are first converted to the same type, and then converted
Forced type conversion
High ----- low
Automatic type conversion
Low ----- high
public class Demo04 { public static void main(String[] args) { int i =128; byte b = (byte)i;//-128 memory overflow //Force conversion of (type) variable names System.out.println(i); System.out.println(b); /* 1 boolean cannot be converted 2 Cannot convert an object type to an unrelated type 3 Force conversion when converting high capacity to low capacity 4 There may be memory overflow or accuracy problems during conversion */ System.out.println("==================="); System.out.println((int)23.7);//23 System.out.println((int)-45.89);//-45 System.out.println("==================="); char c ='a'; int d=c+1; System.out.println(d); System.out.println((char)d); } }
public class Demo05 { public static void main(String[] args) { //When operating large numbers, pay attention to the overflow problem //JD G's latest feature, numbers can be separated by underscores int money =10_0000_0000; int years =20; int total =money*years;//-1474836480, overflow during calculation long total12 = money*years;//The default is int. there is a problem before the conversion? System.out.println(total); System.out.println(total12); long total123 = money*((long)years);//First convert a number to long System.out.println(total123); } }
variable
What is a variable: it is a variable
Java is a strong class language, and every variable must declare its type
Java variable is the most basic storage unit in a program. Its elements include variable name, variable type and scope
matters needing attention
Each variable has a type, which can be either a basic type or a reference type
Variable name must be a legal identifier
A variable declaration is a complete statement, so each variable declaration must end with a semicolon
public class Demo06 { public static void main(String[] args) { int a=1; int b=2; int c=3; //Program readability String name="qingjiang"; char x='X'; double pi=3.14; } }
public class Demo07 { //Class variable static static double salary=2500; //Attributes: Variables //Instance variable: subordinate object. If it is not initialized by itself, the default system of this type is int=0 //boolean value: false by default //The default value is null except for the basic type String name; int age; //main method public static void main(String[] args) { //Resident variables: must declare and initialize values int i=10; System.out.println(i); //Variable type variable name = new Demo07 Demo07 demo07=new Demo07(); System.out.println(demo07.age); System.out.println(demo07.name); //Class variable static System.out.println(salary); } }
constant
constant: the value cannot be changed after initialization! Unchanged value
The so-called constant can be understood as a special variable. After its value is set, it is not allowed to be changed during the operation of the program
final constant type constant name = value
final double PI=3.14
Constant names generally use uppercase characters
public class Demon08 { //static is a modifier. There is no order of precedence, so it can be placed before and after final static final double PI=3.14; public static void main(String[] args) { System.out.println(PI); } }
Naming conventions for variables
All variables, methods and class names: see the meaning of the name
Class member variables: lowercase initial and hump principle: monthSalary except for the first word, the following words are capitalized lastName
Local variables: initial lowercase and hump principle
Constants: uppercase letters and underscores: MAX-VALUE
Class name: initial capitalization and hump principle: Man, GoodMan
Method name: initial lowercase and hump principle: run(), runRun()
operator
package Operator; public class Demo01 { public static void main(String[] args) { int a=10; int b=20; int c=30; int d=11; int e=10; System.out.println(a+b); System.out.println(a/b); System.out.println(d%e); System.out.println((double)a/b); /* 30 0 1 0.5 */ } }
Short circuit operation
false stops
Bitwise Operators
Related to binary
&If both are 1, it is 1; otherwise
|If both are 0, it is 0; otherwise
^Otherwise, two s are the same If two are the same, it is 1; otherwise< shift left * 2
>Shift right / 2
matters needing attention
package Operator; public class Demo03 { public static void main(String[] args) { int a=10; int b=20; System.out.println(""+a+b);//1020 will be output because "" represents that the string is in the front, so the format of subsequent output will also become a string without adding values System.out.println(a+b+"");//30 will be output because the value before the string will be calculated } }
package Operator; public class Demo04 { public static void main(String[] args) { //Ternary operator //Format?: true, the value before: is output; otherwise (false) the value after: is output int a=60; int b=50; String type1=a>=60 ?"qualified" :"unqualified"; String type2=b>=60 ?"qualified" :"unqualified"; System.out.println(type1);//Output qualified System.out.println(type2);//Unqualified output } }
Package mechanism
In order to better organize classes, Java provides a package mechanism to distinguish the namespace of class names. (can be understood as a folder)
The syntax format of the package statement is:
package pkg1[.pkg2[.pkg3...]];
Generally, the inverted company domain name is used as the package name;
In order to use the members of a package, we need to explicitly import the package in the Java program. Use the "import" statement to do this
import package1[.package2...].(classname|*);
(try not to duplicate the package name)
Javadoc
! [Desktop Screenshot 2021.03.05 - 09.11.00.31](C:\Users \ light clouds \ Videos\Desktop\Desktop Screenshot 2021.03.05 - 09.11.00.31.png
Scanner
In the basic syntax we learned before, we didn't realize the interaction between programs and people, but Java provides us with such a tool class that we can get the user's input. java.util.Scanner is a new feature of Java 5. We can get user input through scanner class.
Basic syntax:
Scanner s = new Scanner(System.in);
Get the input string through the next() and nextLine methods of Scanner class. Before reading, we generally need to use hasNextLine() to judge whether there is any input data.
package Scanner; import java.util.Scanner; public class Demo01 { public static void main(String[] args) { //Create a scan object to collect keyboard data Scanner scanner= new Scanner(System.in); System.out.println("use next Reception mode:"); //Judge whether the user enters characters if (scanner.hasNext()) { //Receive in next mode String str= scanner.next(); System.out.println("The output contents are:"+str); } //All classes belonging to IO streams will always occupy resources if they are not closed. We should develop good habits scanner.close(); } }
Receive in next mode:
hello world
The output is hello
package Scanner; import java.util.Scanner; public class Demo02 { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("use NexrLine receive:"); if (scanner.hasNextLine()){ String str = scanner.nextLine(); System.out.println("output:"+str); scanner.close(); } } }
Receive using NexrLine:
hello world
output:hello world
package Scanner; import java.util.Scanner; public class Demo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter:"); String str = scanner.nextLine(); System.out.println("Output:"+str); scanner.close(); } }
matters needing attention
package Scanner; import org.w3c.dom.ls.LSOutput; import java.util.Scanner; public class Demo04 { public static void main(String[] args) { int a; float b; Scanner scanner = new Scanner(System.in); System.out.println("Please enter an integer"); if (scanner.hasNextInt()) { String r = scanner.next(); System.out.println("Integer:" + r); } else { System.out.println("The number you entered is not an integer"); } System.out.println("Please enter decimal"); if(scanner.hasNextFloat()) {String r = scanner.next(); System.out.println("Decimal:"+r); scanner.close(); } } }
package Scanner; import java.util.Scanner; public class Demo05 { public static void main(String[] args) { double sum = 0; int a = 0; Scanner scanner = new Scanner (System.in); while (scanner.hasNextDouble()){ Double x = scanner.nextDouble();//nextDouble note format sum = x + sum; a++; } System.out.println("The total is:"+sum); System.out.println("The average is"+sum/a); scanner.close(); } }
structure
Sequential structure
Select structure
package struct; import java.util.Scanner; public class Demo01 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Double score = scanner.nextDouble(); if (score<60){ System.out.println("had not pass"); }else { System.out.println("pass"); } scanner.close(); } }
public class Demo02 { public static void main(String[] args) { System.out.println("please input your contain"); Scanner scanner = new Scanner(System.in); String contain = scanner.nextLine(); //Variable equals() determines whether the strings are equal; if (contain.equals("hello")){ System.out.println("yeah is hello"); }else{ System.out.println("input errror"); } scanner.close(); } }
please input your contain
hello
yeah is hello
please input your contain
world
input errror
package struct; import java.util.Scanner; public class Demo03 { public static void main(String[] args) { System.out.println("please input score"); Scanner scanner = new Scanner(System.in); double score = scanner.nextDouble(); if (score == 100) { System.out.println("RANK S "); }else if (score >= 90 && score < 100){ System.out.println("RANK A "); }else if (score >= 80 && score < 90){ System.out.println("RANK B "); }else if (score >= 70 && score < 80){ System.out.println("RANK C "); }else if (score >= 60 && score < 70){ System.out.println("RANK D "); }else if (score >= 0 && score < 60){ System.out.println("had not pass "); }else { System.out.println("input error"); } scanner.close(); } }
package struct; public class Demo04 { public static void main(String[] args) { char grade = 'F'; //switch struct need to concern : and break; switch (grade){ case 'A' : System.out.println("excellence"); break; case 'B' : System.out.println("good mark"); break; case 'C' : System.out.println("medium level"); break; case 'D' : System.out.println("pass"); break; default : System.out.println("had not pass"); break; } } }
Extensions: decompilations
Or change the opening method of the class file to Ide
Cyclic structure
package struct; public class Demo05 { public static void main(String[] args) { //output 1-100 int i=0; while (i<100){ System.out.println(++i);//Pay attention to the difference between + + i and i + + } } }
package struct; public class Demo06 { public static void main(String[] args) { int i = 1; int sum = 0; while (i<=100) { sum = sum+i; i++; } System.out.println(sum); } }
package struct; public class Demo07 { public static void main(String[] args) { int i = 0; int sum = 0; do { sum = sum + i; i++; }while (i<=100); System.out.println(sum); } }
package struct; public class Demo08 { public static void main(String[] args) { int i; int sum = 0; for (i=1;i <= 100;i+=2) { System.out.println(i); sum = sum + i; } System.out.println("Odd sum"+sum); System.out.println(sum); sum = 0; for (i=2;i <= 100;i+=2) { System.out.println(i); sum = sum + i; } System.out.println("Even sum is"+sum); System.out.println(sum); } }
package struct; public class Demo09 { //The difference between print and println public static void main(String[] args) { int a = 0; for (int i = 0; i <= 1000; i++) { if (i%5 == 0) { System.out.print(i+"\t"); a++; if(a%3==0){ System.out.println(); } } } } }
package struct; public class Demo10 { public static void main(String[] args) { for (int i = 1; i <= 9; i++) { for (int a = 1; a <= i; a++) { System.out.print(a + "*" + i + "=" + a*i +"\t" ); } System.out.println(); } } }
11=1
12=2 22=4
13=3 23=6 33=9
14=4 24=8 34=12 44=16
15=5 25=10 35=15 45=20 55=25
16=6 26=12 36=18 46=24 56=30 66=36
17=7 27=14 37=21 47=28 57=35 67=42 77=49
18=8 28=16 38=24 48=32 58=40 68=48 78=56 88=64
19=9 29=18 39=27 49=36 59=45 69=54 79=63 89=72 9*9=81
package struct; public class Demo11 { public static void main(String[] args) { int number[] = {10,20,30,40,50}; for(int i=0;i<5;i++){ System.out.println(number[i]); } System.out.println("================================="); //Traversing the elements of an array for (int a : number){ System.out.println(a); } } }
package struct; public class Demo12 { public static void main(String[] args) { for(int i =1;i <= 100;i++){ if (i%10==0) break; System.out.println(i); } } }
1
2
3
4
5
6
7
8
9
package struct; public class Demo12 { public static void main(String[] args) { for(int i =1;i <= 20;i++){ if (i%10==0) continue; System.out.println(i); } } }
1
2
3
4
5
6
7
8
9
11
12
13
14
15
16
17
18
19
package struct; public class Demo13 { //Print triangles public static void main(String[] args) { for (int i = 1; i <= 5; i++) { for (int a = i; a > 0; a--) { System.out.print("*"); } System.out.println(); } } }// * ** *** **** *****
package struct; public class Demo13 { //Print triangles public static void main(String[] args) { for (int i = 5; i > 0; i--) { for (int a = i; a > 0; a--) { System.out.print("*"); } System.out.println(); } } }// ***** **** *** ** *
package struct; public class Demo13 { //Print triangles public static void main(String[] args) { for (int i = 5; i > 0; i--) { for (int a = i; a > 0; a--) { System.out.print(" "); } for (int b = 1; b < (6-i); b++) { System.out.print("*"); } for (int c = 1; c < (6-i); c++) { System.out.print("*"); } System.out.println(); } } }// ** **** ****** ********
method
What is method
package method; public class Demo01 { public static void main(String[] args) { int sum = add(1,2); System.out.println(sum); } public static int add(int a,int b){ return a+b; } }
package method; public class Demo02 { public static void main(String[] args) { number5(); } public static void number5(){ int a = 0; for (int i = 0; i <= 1000; i++) { if (i%5 == 0) { System.out.print(i+"\t"); a++; if(a%3==0){ System.out.println(); } } } } }
Definition of method
Methods in Java are similar to functions in other languages. They are code fragments used to complete specific functions. Generally, defining a method includes the following syntax
Method contains a method header and a method body. The following are all parts of a method:
The modifier tells the compiler how to call the method. Defines the access type of the method
Return value type: a method may have a return value. returnValueType is the data type of the return value of the method. Some methods perform the required operation but do not return a value. In this case, returnValueType is the keyword void
Method name: is the actual name of the method. The method name and parameter table together constitute the method signature
Parameter type: a parameter is like a placeholder. When a method is called, it passes a value to the parameter, which is called an argument or variable. Parameter list refers to the type, order and number of parameters of a method. Parameters are optional, and methods can contain no parameters
Formal parameter: used to receive external input data when the method is called
Argument: the data actually passed to the method when the method is called
Method body: the method body contains specific statements that define the function of the method
package method; public class Demo03 { public static void main(String[] args) { double a=compare(5,5); System.out.println(a); System.out.println(compare(8,9)); } //Specific size public static double compare(double a,double b){ double big=0; if (a == b) { System.out.println("a=b"); return 0;//return in addition to returning a value, you can also end the method } if (a<b){ big = b; }else if (a>b){ big = a; } return big; } }
Method call
Overloading of methods
Overloading is a function with the same function name but different formal parameters in a class.
Rules for method overloading:
Method names must be the same.
The parameter list must be different (different number, different type, different order of parameters, etc.).
The return types of methods can be the same or different.
Just different return types are not enough to overload methods.
Realization theory:
If the method names are the same, the compiler will match one by one according to the number of parameters and parameter types of the calling method to select the corresponding method. If the matching fails, the compiler will report an error.
package method; public class Demo03 { public static void main(String[] args) { double a=compare(5,5); System.out.println(a); System.out.println(compare(8,9)); System.out.println(compare(1,2,3)); } //Specific size public static double compare(double a,double b){ double big=0; if (a == b) { System.out.println("a=b"); return 0;//return in addition to returning a value, you can also end the method } if (a<b){ big = b; }else if (a>b){ big = a; } return big; } public static double compare(double a,double b,double c){ double big = 0; double i = 0; if (a == b && b==c) { System.out.println("a=b=c"); return 0;//return in addition to returning a value, you can also end the method } if (b>a){ i = a; a = b; b = i; }if (c>a){ i = a; a = c; c = a; }if (c>b){ i = b; b = c; c = i; } return a; } }
a=b
0.0
9.0
3.0
Command line parameters
package method; public class Demo04 { public static void main(String[] args) { //args.length array length for (int i=0; i< args.length; i++){ System.out.println("args[" + i + "]:" + args[i]); } } }
Variable parameter
package method; public class Demo05 { public static void main(String[] args) { Demo05 demo05 = new Demo05();//demo05 is an object demo05.text(1); } public void text(int... i){//It is equivalent to defining multiple I's. I's become arrays System.out.println(i[0]); } }
1
package method; public class Demo05 { public static void main(String[] args) { Demo05 demo05 = new Demo05();//demo05 is an object demo05.text(1,2,3,4,5); } public void text(int... i){//It is equivalent to defining multiple I's. I's become arrays //text(int a,int... i)... It needs to be placed on the last parameter System.out.println(i[0]); System.out.println(i[1]); System.out.println(i[2]); System.out.println(i[3]); System.out.println(i[4]); } }
1
2
3
4
5
recursion
public class Recursion1 { public static void main(String[] args) { int[] array=new int[20]; for (int i=0;i<array.length;i++){ System.out.println(recursion(i)); } } public static int recursion(int i) { if (i == 1 || i == 0) { return 1; } else { return recursion(i - 1) + recursion(i - 2); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=53093:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Recursion1 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 Process finished with exit code 0
package method; public class Demo06 { public static void main(String[] args) { System.out.println(f(2)); } public static int f(int n){ if (n==1){ return 1; }else { return n*f(n-1); } } }
Clean Calculator Beta
package method; import java.util.Scanner; public class computer { public static void main(String[] args) { char i = 0; double sum = 0; System.out.println("welcome use my computer"); System.out.println("please input char"); Scanner scanner = new Scanner(System.in); if (scanner.hasNextInt()){ int str = scanner.nextInt(); switch (str){ case 1 : char a='*'; i = a; break; case 2 : char b='/'; i = b; break; case 3 : char c='+'; i = c; break; case 4 : char d='-'; i = d; break; default: System.out.println("input error"); } System.out.println(i); Scanner scanner2 = new Scanner(System.in); System.out.println("please input first number"); if (scanner2.hasNextDouble()){ Double first = scanner2.nextDouble(); System.out.println(first+" "+i); System.out.println("please input second"); Scanner scanner3 = new Scanner(System.in); if (scanner3.hasNextDouble()){ Double second = scanner3.nextDouble(); if(i=='*') System.out.println(first + " "+ i + " " +second + '=' + first*second); if(i=='/') System.out.println(first + " "+ i + " " +second + '=' + first/second); if(i=='+') System.out.println(first + " "+ i + " " +second + '=' + first+second); if(i=='-') System.out.println(first + " "+ i + " " +second + '=' + (first-second) ); //When outputting, pay special attention to what to output } } } } }
array
package Array; public class Demo01 { public static void main(String[] args) { int sum = 0; //Type of variable name of variable = value of variable //Array type int[] nums;//Declare an array //Or int num [] nums = new int[10];//Create an array int[] nusm2 = new int[10]; //Assign values to array elements nums[0] = 1; nums[1] = 2; nums[2] = 3; nums[3] = 4; nums[4] = 5; nums[5] = 6; nums[6] = 7; nums[7] = 8; nums[8] = 9; nums[9] = 10; //array.length array length for (int i = 0;i<nums.length;i++){ System.out.println(nums[i]); sum = sum + nums[i]; //int[] nums; //nums = new int[]; } System.out.println("sum ="+sum); } }
1
2
3
4
5
6
7
8
9
10
sum =55
Process finished with exit code 0
package Array; public class Demo02 { public static void main(String[] args) { //Static initialization declaration plus creation int[] nums = {1,2,3,4,5}; System.out.println(nums[0]); //Manual assignment is called dynamic initialization, and the default value is 0 int[] mans = new int[10]; man[0]=1; } }
Four basic characteristics of arrays
Its length is determined. Once an array is created, its size cannot be changed
Its elements must be of the same type, and mixed types are not allowed.
The elements in the array can be any data type, including basic type and reference type
Array variables are of reference type. Arrays can also be regarded as objects. Each element in the array is equivalent to the member variables of the object.
The array itself is an object, and the objects in Java are in the heap. Therefore, whether the array saves the original type or other object types,
The array object itself is in the heap.
package Array; public class Demo03 { public static void main(String[] args) { int[] arrays = {1,2,3,4,5}; for (int i = 0;i< arrays.length;i++){ System.out.println(arrays[i]); } } }
package Array; public class Demo03 { public static void main(String[] args) { int sum = 0; int max = 0; int[] arrays = {1,2,3,4,5}; for (int i = 0;i< arrays.length;i++){ System.out.println(arrays[i]); } System.out.println("==========================="); for (int i =0;i< arrays.length;i++){ sum+= arrays[i]; } System.out.println(sum); for (int i =1;i< arrays.length;i++){ max = arrays[0]; if(arrays[i]>max) max = arrays[i]; } System.out.println("==========================="); System.out.println("max:"+max); } }
package Array; public class Demo04 { public static void main(String[] args) { //Inside the enhanced for loop is an iterator iterator int[] arrays = {9,8,7,6}; for (int array : arrays){ //(int array represents each number in the array: array name System.out.println(array); } } }
package Array; public class Demo05 { public static void main(String[] args) { int[] num = {1,2,3,4,5}; printNums(num); } public static void printNums(int[] nums){//Remember to put the construction method in the right position for (int i =0;i< nums.length;i++){ System.out.println(nums[i]); } } }
package Array; public class Demo06 { public static void main(String[] args) { //Invert array int[] num={1,2,3,4,5}; printNums(num); System.out.println("======================"); printNums(reverse(num)); } public static void printNums(int[] nums){ for (int i =0;i< nums.length;i++){ System.out.println(nums[i]); } } public static int[] reverse(int[] array){ int[] result = new int[array.length];//Create a new array to receive the value of the previous array for (int i = 0,r = array.length-1;i< array.length;i++,r--){//It should be noted that there are dynamic changes, and which variables should change with it result[r]=array[i]; } return result; } }
package Array; public class Demo07 { public static void main(String[] args) { int[][] array = {{1,2},{3,4},{5,6}}; System.out.println(array[0]);//The output is the object, that is, the object of {1,2} System.out.println(array[0][0]);//1 System.out.println(array.length);//External length System.out.println(array[0].length);//Internal length for (int i =0;i<array.length;i++){ for (int i2 =0;i2<array[i].length;i2++){ System.out.println(array[i][i2]); } } } }
[I@1d251891
1
3
2
1
2
3
4
5
6
Process finished with exit code 0
package Array; import java.lang.reflect.Array; import java.util.Arrays; public class Demo08 { public static void main(String[] args) { int[] array={1,33,44,22,11,99,32}; reverse(array); System.out.println(Arrays.toString(reverse(array))); } public static int[] reverse ( int[] result){ int temp = 0; //Outer circulation, judge how many times we have to go; for (int i =0;i< result.length-1;i++){ for (int j=0;j<result.length-1-i;j++){ if (result[j]>result[j+1]){ temp=result[j+1]; result[j+1]=result[j]; result[j]=temp; } } } return result; } }
package Array; import java.lang.reflect.Array; import java.util.Arrays; public class Demo08 { public static void main(String[] args) { int[] array={1,33,44,22,11,99,32,0}; printNums(reverse(array)); } public static int[] reverse ( int[] result){ int temp = 0; //Outer circulation, judge how many times we have to go; for (int i =0;i< result.length-1;i++){ for (int j=0;j<result.length-1-i;j++){//i was not subtracted after length-1 when i wrote it myself if (result[j]>result[j+1]){ temp=result[j+1]; result[j+1]=result[j]; result[j]=temp; } } } return result; } public static void printNums(int[] nums){ for (int i =0;i< nums.length;i++){ System.out.println(nums[i]); } } }
Sparse array
package Array; public class Demo0 { //Sparse array //1 means black and 2 means white public static void main(String[] args) { int[][] arrayGame = new int[11][11];//Create a frame arrayGame[1][2]=1; arrayGame[2][6]=2; for (int[] sa : arrayGame){//Traversal array System.out.println(sa); }//Because it is a two-dimensional array, it needs to be traversed twice for (int[] sa : arrayGame){//Traverse the array. Note that the traversal has a certain order for (int sad : sa){ System.out.print(sad+"\t"); }//Traverse [0] Traverse a row System.out.println();//Line feed } //Compressed extracted number int sum = 0; for (int i = 0; i < 11; i++) { for (int j = 0; j < 11; j++) { if (arrayGame[i][j]!=0){ sum++; } } } System.out.println("Number of valid values:"+sum); //Create a sparse array int[][] num=new int[sum+1][3]; } }
[I@1d251891
[I@48140564
[I@58ceff1
[I@7c30a502
[I@49e4cb85
[I@2133c8f8
[I@43a25848
[I@3ac3fd8b
[I@5594a1b5
[I@6a5fc7f7
[I@3b6eb2ec
0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 2 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
Number of valid values: 2
object-oriented
Process oriented & object oriented
Process oriented thought
The steps are clear and simple. What to do in the first step and what to do in the second step...
Facing the process, it is suitable to deal with some relatively simple problems
Object oriented thought
Birds of a feather flock together in a classified thinking mode. When thinking about problems, we will first solve what classifications are needed, and then think about these classifications separately. Finally, process oriented thinking is carried out on the details under a certain classification.
Object oriented is suitable for dealing with complex problems and problems requiring multi person cooperation!
For complex things, in order to grasp from the macro level and analyze reasonably as a whole, we need to use object-oriented thinking to analyze the whole system. However, specific to micro operation, it still needs process oriented thinking to deal with it.
What is object oriented
Object oriented programming (oop)
The essence of object-oriented programming is to organize code in the form of classes and data in the form of objects.
abstract
Three characteristics
encapsulation
inherit
polymorphic
From the perspective of epistemology, there are categories first and then objects. Objects are concrete things. Class is abstract, which is the abstraction of objects
From the perspective of code operation, there are classes before objects. A class is a template for an object.
Review methods and calls
Definition of method
Modifier
Return type
break: jump out of the switch and end the loop
Method name: pay attention to the specification and know the meaning according to the name
Parameter list: (parameter type, parameter name)...
Exception thrown:
Method call
Static method
Non static method
Formal and argument
Value passing and reference passing
this keyword
package Oop; //Demo01 class public class Demo01 { //main method public static void main(String[] args) { } /* Modifier return value type method name (){ //Method body return Return value */ //return end method returns the result public String sayHello(){ return "Hellow world"; } public int max(int a,int b){ return a>b ? a : b;//Ternary operator } }
package Oop; public class Demo02 { //Static static method uses the public memory space, which means that all objects can be referenced directly. There is no need to create objects and then use this method. public static void main(String[] args) { Student.say(); //Non static method //Instantiate this class //Example method 1 new Student().say2(); //Example method 2 //Object type object name object value Student stu = new Student(); stu.say2(); } }
package Oop; //Student class public class Student { //method public static void say(){ System.out.println("The students don't speak"); } public void say2(){ System.out.println("All the students speak"); } }
package Oop; public class Demo03 { public static void a(){ b();//Static methods can call the methods loaded with the class at the same time } public static void b(){ } //Class is generated after instantiation public void c(){ } }
package Oop; public class Demo04 { public static void main(String[] args) { //Argument add(1,2);//Note that formal parameters and arguments should be consistent System.out.println(add(1,2)); } public static int add(int a,int b){//Formal parameter return a+b; } }
package Oop; public class Demo05 { //pass by value public static void main(String[] args) { int a = 1; System.out.println(a);//so 1 change(a); System.out.println(a);// so 1 } //Note: the return value is null public static void change(int a){ a = 10; } }
package Oop; public class Demo06 { //Is reference passing object essence or value passing public static void main(String[] args) { Person person = new Person(); System.out.println(person.name);//null change(person); System.out.println(person);//person is an object System.out.println(person.name);//leaf } //Defines a Person class with an attribute: name public static void change(Person person){ person.name = "leaf"; } } class Person{ String name; }
null
Oop.Person@48140564
leaf
Relationship between class and variable
package Oop; //A project should have only one main method public class Application { public static void main(String[] args) { //Class: abstract, instantiated //Class will return its own object after instantiation //The student object is a concrete instance of the Students class Students xiaoming = new Students(); Students xiaohong = new Students(); xiaohong.age = 3; xiaohong.name="xiao hong"; System.out.println(xiaohong.name); System.out.println(xiaohong.age); /* Calling a class is equivalent to calling a special method. When you create an object (special class), you need to call the variable in the class, method: object Variable name (normal assignment) .Can be understood as Li; */ } }
package Oop; //Student class public class Students { //Properties: Fields String name;//null int age;//0 //method public void study(){ System.out.println(this.name+"I'm learning"); } }
xiao hong
3
package Oop; //A project should have only one main method public class Application { public static void main(String[] args) { //Class: abstract, instantiated //Class will return its own object after instantiation //The student object is a concrete instance of the Students class Students xiaoming = new Students(); Students xiaohong = new Students(); xiaohong.age = 3; xiaohong.name="xiao hong"; System.out.println(xiaohong.name); System.out.println(xiaohong.age); System.out.println(xiaoming.name);//null System.out.println(xiaoming.age);//0 /* Calling a class is equivalent to calling a special method. When you create an object (special class), you need to call the variable in the class, method: object Variable name (normal assignment) */ } }
constructor
package Text; public class Demo01 { public static void main(String[] args) { Person person = new Person();//The ability to create an object to indicate the existence of an architect /* Public Person{ } */ System.out.println(person.name); } }
package Text; public class Person { //If a function writes nothing, it will also have a method //Display definition constructor String name; //Instantiation initial value //To use the new keyword, you must have a constructor //Used to initialize values public Person(){ this.name="leaf"; } //Parameterized Construction: once a parameterized construction is defined and there is no parameter, the definition must be displayed public Person(String name){ this.name=name;//The previous name is defined in the class, and the last name is entered by () } //The above two methods are overloaded }
constructor
1 is the same as the class name
2 no return value
effect
1new essence lies in the construction method
2 value of initialization object
Note:
1 after defining a parameterized structure, if you want to use a parameterless structure, you can define a parameterless structure
Create object memory analysis
package Text; public class Pet { String name; int age; public void shout(){ System.out.println("Let out a cry"); } }
package Text; public class Application { public static void main(String[] args) { Pet dog = new Pet();//Call class to create object dog.name="Wangcai"; dog.age=13; dog.shout(); System.out.println(dog.age); System.out.println(dog.name); } }
package Text; public class Reveive { /* 1.Classes and objects A class is a template: abstract, and an object is a concrete instance 2.method Define, call 3.Corresponding reference Reference type: basic type (8) Objects are operated by reference: stack -- "heap" 4.Attribute: Field member variable Default initialization: Number: 0.0 char : u0000 boolean: false Reference: null Modifier attribute type attribute name = attribute value 5.Object creation and use You must use the new keyword to create an object, and the constructor Person pet = new Person(); Object's properties pet name Object sleep() 6 class Static properties Dynamic behavior method Encapsulation inheritance polymorphism */ }
encapsulation
package Text; public class Demo02 { public static void main(String[] args) { //Private properties cannot be called directly //It needs to be called through another method /* 1.Improve program security 2.Implementation details of hidden code 3.Unified interface 4.Increased system maintainability */ Student name = new Student(); name.setName("xiao ming"); System.out.println(name.getName()); Student age = new Student(); age.setAge(999); System.out.println(age.getAge()); age.setAge(99); System.out.println(age.getAge()); } }
package Text; public class Student { //Private property private String name; private int age; //Create a method that calls a private property public String getName(){// Get this data from the file calling this class //Note the return type return this.name; } public void setName(String name){//Set a value for this data this.name=name; } public int getAge() { return age; } public void setAge(int age) { //Set can set the scope to make the program specification more secure if (age<120 && age>0){ this.age = age; } else { System.out.println("you is 3 years people"); } } }
inherit
A class decorated with final cannot be inherited
package Text; public class Father { public int money; public String wantsay; public String getWantsay(){ return this.wantsay; } public void setWantsay(String wantsay){ this.wantsay=wantsay; } }
package Text; public class Sun extends Father {//Inherits a parent class. Private properties of a parent class cannot be inherited }
package Text; public class T { public static void main(String[] args) { Sun sun=new Sun(); sun.setWantsay("thanks my father"); System.out.println(sun.getWantsay()); } }
thanks my father
package Text; public class T { //public //protected //default //private //In Java, all classes inherit the object class by default public static void main(String[] args) { Sun sun=new Sun(); sun.setWantsay("thanks my father"); System.out.println(sun.getWantsay()); } }
super
package Text; public class Father { public int money; protected String name = "yezi"; public String wantsay; public Father() { System.out.println("father No reference"); } public String getWantsay(){ return this.wantsay; } public void setWantsay(String wantsay){ this.wantsay=wantsay; } public void print(){ System.out.println("father"); } }
package Text; public class Sun extends Father {//Inherit parent class public Sun() { System.out.println("sun No parameter of subclass");//Here is the hidden super code that calls the parent class without parameters } private String name ="leaf"; public void Text(String name){ System.out.println(name); System.out.println(this.name); System.out.println(super.name);//super subclass calls parent class (method or parameter) } public void print(){ System.out.println("sun"); } public void text1(){ print();//itself this.print();//In this class super.print();//Parent class } }
package Text; public class T { //public //protected //default //private //In Java, all classes inherit the object class by default public static void main(String[] args) { Sun sun=new Sun();//No parameters in the calling class will be executed when calling (when the object is created). At the same time, if no parameters of the subclass are called, no parameters of the parent class will also be executed (the parent will be executed before the child) //If a subclass wants to call the parameterless construction of the parent class, it must ensure that the parent class has no parameters, otherwise the subclass cannot write parameterless bqd (may mean calling static methods) sun.setWantsay("thanks my father"); System.out.println(sun.getWantsay()); Sun name=new Sun(); name.Text("yzm"); sun.text1(); } }
Nonparametric subclass sun
thanks my father
No parameters of sun subclass
yzm
leaf
yezi
sun
sun
father
Process finished with exit code 0
package Text; public class F { public static void text(){ System.out.println("F==text"); } public void text2(){ System.out.println("F"); } }
package Text; public class S extends F{ public static void text(){ System.out.println("S==text"); } public void text2(){ System.out.println("S"); } }
package Text; public class T2 { //There is a difference between calling static methods and non static methods public static void main(String[] args) { //Calling static methods is generally related to the class on the left (defined data type) F f = new F(); f.text(); F s = new S(); s.text(); /* F==text F==text */ //Call non static method F f2 = new F(); f2.text2(); F s2 = new S();//The subclass overrides the method of the parent class, which only appears in the non static method, or when calling the non static method (the subclass calls the parent class), look at the new object behind it s2.text2(); /* F S */ } }
summary
super note
1.super must call the constructor of the parent class in the first place of the constructor
2.super must only appear in the methods or constructions of subclasses
3.super and this cannot call construction methods at the same time
this:
The objects represented are different:
This: this object is called by itself
super: represents the application of the parent object
premise
this: it can be used without inheritance
super: can only be used under inheritance conditions
Construction method
this(); Construction of this class
super(); Construction of parent class
Rewriting: there needs to be an inheritance relationship. The subclass rewrites the method of the parent class
1. / method name must be the same
2. The parameter list must be the same
3. Modifier: the scope can be expanded but not reduced: public "protected" default "private
4. Exception thrown: the range can be narrowed but not expanded: classnotfoundexception -- > exception()
When overridden, the methods of subclasses and superclasses must be consistent; Different methods!
Why rewrite
1. The function of the parent class and the subclass are not necessarily required or satisfied!
alt+insert: override
polymorphic
package Text; public class Person02 { public void run(){ System.out.println("person run"); } }
package Text; public class Student02 extends Person02{ public void run(){ System.out.println("student run"); } public void eat(){ System.out.println("eat"); } }
package Text; public class Text02 { public static void main(String[] args) { Person02 person02=new Student02(); Person02 person03=new Person02(); Student02 person04=new Student02(); Object p=new Student02(); person02.run();//The subclass overrides the method of the parent class person03.run(); person04.run(); //person02.eat cannot be called, because now only subclasses have method overloading, which is equivalent to calling the parent class //Which methods can be executed by the object mainly depends on the type on the left, the relationship between the right change and the method called //Methods that can be called by their own parent and child classes //A parent type can point to a subclass, but cannot call methods unique to a subclass person04.eat(); } }
ackage Text; public class Text02 { //Now there is this relationship //Object>Person02>Student02 //Object>Person02>Teacher //Instanceof is to judge whether (object) a instanceof b (class) object a is a child of b Class or class a true false public static void main(String[] args) { Object obj=new Student02(); System.out.println(obj instanceof Object); System.out.println(obj instanceof Person02); System.out.println(obj instanceof Student02); System.out.println(obj instanceof String);//false peer relationship System.out.println(obj instanceof Teacher);//false Person02 person02=new Person02(); System.out.println(person02 instanceof Object);//true System.out.println(person02 instanceof Person02);//true System.out.println(person02 instanceof Student02);//false } }
package Text2; public class Application { //Type conversion can also be performed between parent and son //When a subclass has a method but the parent class does not, it cannot use the subclass's method by calling the parent class. At this time, type conversion is used public static void main(String[] args) { Person person=new Student(); //Cannot call person studentonly Student student=(Student) person;//Forced conversion ((Student) person).studentonly(); Student s1=new Student(); Person person1=s1;//A reference to a parent class can point to an object of a child class //Turning a subclass into a parent class may lose its original methods //Convert a parent class to a child class and cast it downward } }
static
Static code block > anonymous code block > construction method
package Text2; public class Text { { System.out.println("Anonymous code block"); } static {//static exists as soon as the class appears System.out.println("Static code block"); } public Text() { System.out.println("Construction method"); } public static void main(String[] args) { Text text=new Text();//The method is executed because the object is to be created } }
Static code block
Anonymous code block
Construction method
package Text2; public class Text { { System.out.println("Anonymous code block"); } static {//static is a class that exists as soon as it appears. It only performs this function once System.out.println("Static code block"); } public Text() { System.out.println("Construction method"); } public static void main(String[] args) { Text text1=new Text();//The method is executed because the object is to be created System.out.println("================"); Text text2=new Text(); } }/* Static code block Anonymous code block Construction method ================ Anonymous code block Construction method */
package Text2; public class T { public static void main(String[] args) { System.out.println(Math.random()); } }
package Text2; import static java.lang.Math.random;//Static import package import static java.lang.Math.PI; public class T { public static void main(String[] args) { System.out.println(random()); System.out.println(PI); } }
package Demo01; public class B extends A{//If you inherit an abstract class, you must implement its methods unless the subclass is also an abstract class (to be inherited by the subclass) @Override public void cxff() { //You can't use new abstract classes. You can only rely on subclasses to implement them //Ordinary methods can be written in abstract classes //Abstract methods must be written in abstract classes //Abstract constraints //Abstract meaning is abstracted to improve development efficiency } }
package Demo01; //abstract class public abstract class A { //Abstract method public abstract void cxff();//Constraint: the general method has only name and no framework (Implementation) }
Interface
package Demo02; //Interface: implemented through interface modification //There can only be simple methods in the interface //And all methods in the interface are abstract public interface TimeServer { void text1(); void text2(); void text3(); void text4(); }
package Demo02; public interface UseService { void use1(); void use2(); }
package Demo02; //Implement the interface using implements: implement the interface to be implemented...... The implementation name is usually suffixed with Impl public class UseTimeServeImpl implements TimeServer ,UseService{ //Interfaces can inherit multiple //Multiple inheritance is realized on the side //The class that implements the interface must override the method of the interface @Override public void text1() { } @Override public void text2() { } @Override public void text3() { } @Override public void text4() { } @Override public void use1() { } @Override public void use2() { } }
effect:
1. Constraints
2. Define some methods for different people to realize -! 10——————1
3.public abstract
4.public static final
5. The interface cannot be instantiated - there is no construction method in the interface-
6. Implementation can realize multiple functions
7. The method in the interface must be rewritten
Inner class
package Demo03; public class Text { public static void main(String[] args) { //new an external class first Outer outer=new Outer(); outer.out(); //Through outer To call the inner class in the outer class Outer.Inter inter= outer.new Inter(); inter.in(); //Internal classes can call private properties and methods of external classes inter.geti(); } }
private int i=10; private void o(){ System.out.println("I am a private method of an external class"); } public void out() { System.out.println("I'm an external class"); } public class Inter{ public void in() { System.out.println("I'm an internal class"); } public void geti(){ System.out.println(i); } } }
//If the external class is non static, you cannot directly access the static internal class unless both are static
package Demo03; public class Out { public void i(){ class inner{ //Local inner class } } }
abnormal
Simple classification
Exception architecture
Error
Exception
Exception handling mechanism
package Demo04; public class Text { public static void main(String[] args) { int a=1; int b=0; try {//Monitoring area System.out.println(a/b); }catch (ArithmeticException e){//Catch the type of exception you want to catch System.out.println("error"); }finally {//Deal with the aftermath System.out.println("finally"); } } }
error
finally
public static void main(String[] args) { int a=1; int b=0; try {//Monitoring area System.out.println(a/b); }catch (ArithmeticException e){//Catch the type of exception you want to catch System.out.println("ari"); //There can be multiple catch catches, but the exception level is mix big }catch (Error e){ System.out.println("err"); }catch (Exception e){ System.out.println("exc"); } catch (Throwable t){ System.out.println("thr"); }finally { System.out.println("finally"); } } }
public class Text2 { public static void main(String[] args) { int a=1; int b=0; try { System.out.println(a/b); } catch (Exception e) { System.exit(1);//You can end the program early e.printStackTrace();//Print wrong stack information } //Select CTRL+alt+t to generate code quickly } }
package Demo04; public class Demo03 { //Actively throwing exceptions is generally used in methods public static void main(String[] args) { try { new Demo03().text(1,0); } catch (ArithmeticException e) { e.printStackTrace(); } finally { } } //If you can't handle this exception in this method, you can throw it out public void text(int a ,int b)throws ArithmeticException{ if (b==0){ //throw throws throw new ArithmeticException(); } } }
Custom exception
package Demo05; public class MyException extends Exception { //Transmitting numbers 10 private int detail; public MyException(int a){//constructor this.detail=a; } //toString: abnormal print information @Override public String toString() { return "MyException{" + "detail=" + detail + '}'; } }
package Demo05; public class Text { //There may be abnormal methods static void text(int a)throws MyException{ System.out.println("The parameters passed are:"+a); if (a>10){ throw new MyException(a);//Thrown into MyException constructor (method) } System.out.println("ok"); } public static void main(String[] args) { try { text(11); } catch (MyException e) {//Capture error System.out.println("MyExpection"+e); e.printStackTrace(); } } }
aggregate
1.1 collection overview
Characteristics of collection class: it provides a storage model with variable storage space, and the stored data capacity can be changed
ArrayList
There are many collection classes. Learn ArrayList first
Arraylist:
Resizable array implementation
Generic is a special data type
Where E appears, we can replace it with reference data type
Example: Arraylist,ArrayList
package Test1; import java.util.ArrayList; public class T1 { public static void main(String[] args) { ArrayList<String> array = new ArrayList<String>(); array.add("Hello"); array.add("world"); array.add("JavaSe"); System.out.println(array); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=58818:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Test1.T1 [Hello, world, JavaSe] Process finished with exit code 0
package Test1; import java.util.ArrayList; public class T1 { public static void main(String[] args) { ArrayList<String> array = new ArrayList<String>(); array.add("Hello"); array.add("world"); array.add("JavaSe"); System.out.println(array.remove(0));//Remove and return the removed value System.out.println(array); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=58845:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Test1.T1 Hello [world, JavaSe] Process finished with exit code 0
package Test1; import java.util.ArrayList; public class T1 { public static void main(String[] args) { ArrayList<String> array = new ArrayList<String>(); array.add("Hello"); array.add("world"); array.add("JavaSe"); //System.out.println(array.remove(0));// Remove and return the removed value (array subscript modification method) System.out.println(array.remove("world"));//Remove and return boolean value (element array modification method) System.out.println(array); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=58865:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Test1.T1 true [Hello, JavaSe] Process finished with exit code 0
package Test1; import java.util.ArrayList; public class T1 { public static void main(String[] args) { ArrayList<String> array = new ArrayList<String>(); array.add("Hello"); array.add("world"); array.add("JavaSe"); //System.out.println(array.remove(0));// Remove and return the removed value (array subscript modification method) //System.out.println(array.remove("world"));// Remove and return boolean value (element array modification method) System.out.println(array.set(1,"WORLD"));//Modify and return the modified value System.out.println(array); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=58923:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Test1.T1 world [Hello, WORLD, JavaSe] Process finished with exit code 0
package Test1; import java.util.ArrayList; public class T1 { public static void main(String[] args) { ArrayList<String> array = new ArrayList<String>(); array.add("Hello"); array.add("world"); array.add("JavaSe"); //System.out.println(array.remove(0));// Remove and return the removed value (array subscript modification method) //System.out.println(array.remove("world"));// Remove and return boolean value (element array modification method) //System.out.println(array.set(1,"WORLD"));// Modify and return the modified value System.out.println(array.size());//Number of arrays System.out.println(array); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=58933:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Test1.T1 3 [Hello, world, JavaSe] Process finished with exit code 0
public class T1 { public static void main(String[] args) { ArrayList<String> array = new ArrayList<String>(); array.add("Hello"); array.add("world"); array.add("JavaSe"); //System.out.println(array.remove(0));// Remove and return the removed value (array subscript modification method) //System.out.println(array.remove("world"));// Remove and return boolean value (element array modification method) //System.out.println(array.set(1,"WORLD"));// Modify and return the modified value //System.out.println(array.size());// Number of arrays System.out.println(array.get(2));//Get this element System.out.println(array); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=58962:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Test1.T1 JavaSe [Hello, world, JavaSe] Process finished with exit code 0
Manage student System(unfinish)
package Java1; import java.util.ArrayList; import java.util.Scanner; public class managesystem { public static void main(String[] args) { ArrayList<Student> array=new ArrayList<Student>(); while(true) { System.out.println("--------Welcome to student management system--------"); System.out.println("1.Add student"); System.out.println("2.Delete student"); System.out.println("3.View all students"); System.out.println("4.sign out"); System.out.println("Please enter your choice:"); Scanner scanner = new Scanner(System.in); switch (scanner.nextInt()) { case 1:addStudent(array); break; case 3:outStudentData(array); break; } } } public static void addStudent(ArrayList<Student> array){ Scanner s1=new Scanner(System.in); Student s=new Student(); System.out.println("please input student id"); String id=s1.nextLine(); s.setId(id); System.out.println("please input student name"); String name=s1.nextLine(); s.setName(name); System.out.println("please student age"); String age=s1.nextLine(); s.setAge(age); System.out.println("please input address"); String address=s1.nextLine(); s.setAddress(address); array.add(s); } public static void outStudentData(ArrayList<Student> array){ System.out.println(array.size()); System.out.println(array.get(0)); for (int i=0;i< array.size();i++){ Student s = array.get(i);//Extract collection object System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getAge()+"\t"+s.getAddress()); } } } class Student{ private String name; private String age; private String address; private String id; public Student(){} public Student(String name,String age,String address,String id){ this.name=name; this.id=id; this.address=address; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
Architecture of collection classes
package Java1; import java.util.ArrayList; import java.util.Collection; public class Collection1 { public static void main(String[] args) { Collection<String> c=new ArrayList<String>(); c.add("Hello"); c.add("World"); c.add("Java"); System.out.println( c.add("Hello")); System.out.println(c); System.out.println(c.size());//Judge set length System.out.println("==========="); System.out.println(c); System.out.println(c.remove("Hello")); System.out.println("============"); System.out.println(c); System.out.println(c.contains("World"));//Determine whether this value exists in the collection System.out.println("============"); System.out.println(c); System.out.println( c.isEmpty());//Judge whether the set is empty System.out.println("============"); System.out.println(c); c.clear();//Clear collection System.out.println(c); } }
true [Hello, World, Java, Hello] 4 =========== [Hello, World, Java, Hello] true ============ [World, Java, Hello] true ============ [World, Java, Hello] false ============ [World, Java, Hello] [] Process finished with exit code 0
package Java1; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; public class Iterator1 { public static void main(String[] args) { Collection<String> c=new ArrayList<String>(); c.add("Hello"); c.add("java"); c.add("world"); Iterator<String> it=c.iterator();//Iterator is a interface System.out.println(it.next()); System.out.println(it.next()); System.out.println(it.next()); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=53424:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.Iterator1 Hello java world Process finished with exit code 0
package Java1; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; public class Iterator1 { public static void main(String[] args) { Collection<String> c=new ArrayList<String>(); c.add("Hello"); c.add("java"); c.add("world"); Iterator<String> it=c.iterator();//Iterator is a interface // System.out.println(it.next()); // System.out.println(it.next()); // System.out.println(it.next()); if (it.hasNext()){ System.out.println(it.next()); } if (it.hasNext()){ System.out.println(it.next()); } if (it.hasNext()){ System.out.println(it.next()); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=53614:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.Iterator1 Hello java world Process finished with exit code 0
package Java1; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; public class Iterator1 { public static void main(String[] args) { Collection<String> c=new ArrayList<String>(); c.add("Hello"); c.add("java"); c.add("world"); Iterator<String> it=c.iterator();//Iterator is a interface // System.out.println(it.next()); // System.out.println(it.next()); // System.out.println(it.next()); // if (it.hasNext()){ // System.out.println(it.next()); // } // if (it.hasNext()){ // System.out.println(it.next()); // } // if (it.hasNext()){ // System.out.println(it.next()); // } while (it.hasNext()){ String s=it.next(); System.out.println(s); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=53640:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.Iterator1 Hello java world Process finished with exit code 0
To use a collection
case
package Java1; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class CollectionDemo { //establish object of collection public static void main(String[] args) { Collection<Student> collection=new ArrayList<Student>(); Student s1=new Student("Zhang Manyu","19","Hk","1"); Student s2=new Student("Wang Zuxian","26","Hk","2"); Student s3=new Student("Zhou Runfa","91","Hk","3"); collection.add(s1); collection.add(s2); collection.add(s3); Iterator<Student> ite=collection.iterator(); while (ite.hasNext()){ Student st=ite.next(); System.out.println(st.getId()+" "+st.getName()+" "+st.getAge()+" "+st.getAddress()); }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=54073:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.CollectionDemo 1 Zhang Manyu 19 Hk 2 Wang Zuxian 26 Hk 3 Zhou Runfa 91 Hk Process finished with exit code 0
List
The usage is similar to ArrayList
package Java1; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ListDemo { public static void main(String[] args) { List<Student> list=new ArrayList<Student>(); Student s1 =new Student("Lizeyang","19","Jy","1"); Student s2 =new Student("Lize","19","Jy","2"); Student s3 =new Student("Li","19","Jy","3"); list.add(s1); list.add(s2); list.add(s3); Iterator<Student> it=list.iterator(); while (it.hasNext()){ Student st=it.next(); System.out.println(st.getId()+" "+st.getName()+" "+st.getAge()+" "+st.getAddress()); } System.out.println("============="); for (int i =0;i<list.size();i++){ Student st=list.get(i); System.out.println(st.getId()+" "+st.getName()+" "+st.getAge()+" "+st.getAddress()); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=54790:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.ListDemo 1 Lizeyang 19 Jy 2 Lize 19 Jy 3 Li 19 Jy ============= 1 Lizeyang 19 Jy 2 Lize 19 Jy 3 Li 19 Jy
Concurrent modification exception
package Test1; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class T2 { public static void main(String[] args) { List<String> list=new ArrayList<String>(); list.add("Hello"); list.add("java"); list.add("world"); Iterator<String> it=list.iterator(); while (it.hasNext()){ String s= it.next(); if (s.equals("java")){ list.add("se"); } } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=57538:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Test1.T2 Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1043) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:997) at Test1.T2.main(T2.java:15) Process finished with exit code 1
Source code analysis:
private void checkForComodification(final int expectedModCount) { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } }
ListIterator
package Java1; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.ListIterator; public class Listiterrator1 { public static void main(String[] args) { List c=new ArrayList<String>(); c.add("Hello"); c.add("java"); c.add("world"); ListIterator<String> list=c.listIterator(); while (list.hasNext()){ System.out.println(list.next()); } System.out.println("=============="); while(list.hasPrevious()){ System.out.println(list.previous()); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=57382:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.Listiterrator1 Hello java world ============== world java Hello Process finished with exit code 0
package Java1; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.ListIterator; public class Listiterrator1 { public static void main(String[] args) { List c=new ArrayList<String>(); c.add("Hello"); c.add("java"); c.add("world"); ListIterator<String> list=c.listIterator(); while (list.hasNext()){ System.out.println(list.next()); } System.out.println("=============="); while(list.hasPrevious()){ System.out.println(list.previous()); } System.out.println("==============="); while (list.hasNext()){ String s=list.next(); if (s.equals("Hello")){ list.add("my"); } } System.out.println(c); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=57687:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.Listiterrator1 Hello java world ============== world java Hello =============== [Hello, my, java, world] Process finished with exit code 0
package Java1; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ListDemo { public static void main(String[] args) { List<Student> list=new ArrayList<Student>(); Student s1 =new Student("Lizeyang","19","Jy","1"); Student s2 =new Student("Lize","19","Jy","2"); Student s3 =new Student("Li","19","Jy","3"); list.add(s1); list.add(s2); list.add(s3); Iterator<Student> it=list.iterator(); while (it.hasNext()){ Student st=it.next(); System.out.println(st.getId()+" "+st.getName()+" "+st.getAge()+" "+st.getAddress()); } System.out.println("============="); for (int i =0;i<list.size();i++){ Student st=list.get(i); System.out.println(st.getId()+" "+st.getName()+" "+st.getAge()+" "+st.getAddress()); } System.out.println("============="); for (Student st: list){ System.out.println(st.getId()+" "+st.getName()+" "+st.getAge()+" "+st.getAddress()); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=58558:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.ListDemo 1 Lizeyang 19 Jy 2 Lize 19 Jy 3 Li 19 Jy ============= 1 Lizeyang 19 Jy 2 Lize 19 Jy 3 Li 19 Jy ============= 1 Lizeyang 19 Jy 2 Lize 19 Jy 3 Li 19 Jy Process finished with exit code 0
data structure
package Test1; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class T3 { public static void main(String[] args) { ArrayList<String> array=new ArrayList<String>(); array.add("I"); array.add("am"); array.add("Jone"); for (String s:array){ System.out.println(s); } System.out.println("=================="); for (int i= 0;i<array.size();i++){ System.out.println(array.get(i)); } System.out.println("=================="); Iterator<String> it=array.iterator(); while(it.hasNext()){ String s=it.next(); System.out.println(s); } System.out.println("=================="); List<String> listIterator=new ArrayList<String>() ; listIterator.add("He"); listIterator.add("is"); listIterator.add("college"); for (String s:listIterator){ System.out.println(s); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=59481:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Test1.T3 I am Jone ================== I am Jone ================== I am Jone ================== He is college Process finished with exit code 0
Linklist
package Java1; import java.util.LinkedList; public class Linklist { public static void main(String[] args) { LinkedList list=new LinkedList(); list.add("Hello"); list.add("java"); list.add("world"); list.addFirst("first"); list.addLast("final"); System.out.println(list); System.out.println("============="); System.out.println(list.removeFirst()); System.out.println(list); System.out.println(list.removeLast()); System.out.println(list); System.out.println("================"); System.out.println(list.set(1,"not")); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=62252:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.Linklist [first, Hello, java, world, final] ============= first [Hello, java, world, final] final [Hello, java, world] ================ java Process finished with exit code 0
Set
package Java1; import java.util.HashSet; import java.util.Set; public class Set1 { public static void main(String[] args) { Set<String> set=new HashSet<>(); set.add("Hello"); set.add("java"); set.add("world"); System.out.println(set); set.add("java");//HashSet cannot add duplicate elements System.out.println(set); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=62397:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.Set1 [java, world, Hello] [java, world, Hello] Process finished with exit code 0
Hashcode
package Java1; public class Hashcode { public static void main(String[] args) { Student s1=new Student("li","19","mei","1"); System.out.println(s1.hashCode()); System.out.println(s1.hashCode()); System.out.println("================"); System.out.println("Hello".hashCode()); System.out.println("java".hashCode()); //By default, different objects have different hashcodes. You can create a new hashCode method to return the same value } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=62533:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.Hashcode 1209271652 1209271652 ================ 69609650 3254818 Process finished with exit code 0
HashSet
Similar to Set
HashCode source code analysis to ensure that the collection is not repeated
Data structure - hash table
Write student class with HashSet
package Java1; import java.util.HashSet; public class HashSet1 { public static void main(String[] args) { HashSet<Student> hs=new HashSet<Student>(); Student s1=new Student("li","19","j","1"); Student s2=new Student("li","20","j","2"); Student s3=new Student("li","21","j","3"); Student s4=new Student("li","19","j","1"); hs.add(s1); hs.add(s2); hs.add(s3); hs.add(s4); for (Student s:hs){ System.out.println(s); } for (Student s:hs){ System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getAge()+"\t"+s.getAddress()); } //Because hashset needs to ensure the uniqueness of the student object, we need to rewrite the hash value in the student class //Because Student is a defined data type and has no statement to judge the hash value and content, it needs to be rewritten } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=63337:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.HashSet1 Java1.Student@48140564 Java1.Student@49e4cb85 Java1.Student@7c30a502 Java1.Student@58ceff1 1 li 19 j 1 li 19 j 3 li 21 j 2 li 20 j Process finished with exit code 0
package Java1; import java.util.HashSet; public class HashSet1 { public static void main(String[] args) { HashSet<Student> hs=new HashSet<Student>(); Student s1=new Student("li","19","j","1"); Student s2=new Student("li","20","j","2"); Student s3=new Student("li","21","j","3"); Student s4=new Student("li","19","j","1"); hs.add(s1); hs.add(s2); hs.add(s3); hs.add(s4); for (Student s:hs){ System.out.println(s); } for (Student s:hs){ System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getAge()+"\t"+s.getAddress()); } //Because hashset needs to ensure the uniqueness of the student object, we need to rewrite the hash value in the student class } }
package Java1; import java.util.ArrayList; import java.util.Objects; import java.util.Scanner; public class managesystem { public static void main(String[] args) { ArrayList<Student> array=new ArrayList<Student>(); while(true) { System.out.println("--------Welcome to student management system--------"); System.out.println("1.Add student"); System.out.println("2.Delete student"); System.out.println("3.View all students"); System.out.println("4.sign out"); System.out.println("Please enter your choice:"); Scanner scanner = new Scanner(System.in); switch (scanner.nextInt()) { case 1:addStudent(array); break; case 3:outStudentData(array); break; } } } public static void addStudent(ArrayList<Student> array){ Scanner s1=new Scanner(System.in); Student s=new Student(); System.out.println("please input student id"); String id=s1.nextLine(); s.setId(id); System.out.println("please input student name"); String name=s1.nextLine(); s.setName(name); System.out.println("please student age"); String age=s1.nextLine(); s.setAge(age); System.out.println("please input address"); String address=s1.nextLine(); s.setAddress(address); array.add(s); } public static void outStudentData(ArrayList<Student> array){ System.out.println(array.size()); System.out.println(array.get(0)); for (int i=0;i< array.size();i++){ Student s = array.get(i);//Extract collection object System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getAge()+"\t"+s.getAddress()); } } } class Student{ private String name; private String age; private String address; private String id; public Student(){} public Student(String name,String age,String address,String id){ this.name=name; this.id=id; this.address=address; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return Objects.equals(name, student.name) && Objects.equals(age, student.age) && Objects.equals(address, student.address) && Objects.equals(id, student.id); } @Override public int hashCode() { return Objects.hash(name, age, address, id); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=63375:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.HashSet1 Java1.Student@646e613 Java1.Student@6473c6c Java1.Student@64738aa 1 li 19 j 3 li 21 j 2 li 20 j Process finished with exit code 0
LinkedHashSet
package Java1; import java.util.LinkedHashSet; public class LinkedHashSet1 { public static void main(String[] args) { LinkedHashSet<String> linkedHashSet=new LinkedHashSet<String>(); linkedHashSet.add("Hello"); linkedHashSet.add("java"); linkedHashSet.add("world"); for (String s:linkedHashSet){ System.out.println(s); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=63554:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.LinkedHashSet1 Hello java world Process finished with exit code 0
TreeSet
package Java1; import java.util.TreeSet; public class TreeSet1 { public static void main(String[] args) { TreeSet<Integer> treeSet=new TreeSet<Integer>(); treeSet.add(20); treeSet.add(10); treeSet.add(70); treeSet.add(990); treeSet.add(210); treeSet.add(120); treeSet.add(120); for (Integer i:treeSet){ System.out.println(i); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=63665:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.TreeSet1 10 20 70 120 210 990 Process finished with exit code 0
Use of natural sorting comparable
package Java1; import java.util.TreeSet; public class Comparable1 { public static void main(String[] args) { TreeSet<Student> ts= new TreeSet<Student>(); Student s1 = new Student("Yangyuhuan","28","XA","1"); Student s2 =new Student("Diaochan","29","CA","2"); Student s3 = new Student("Wangzhaojun","30","GD","3"); ts.add(s1); ts.add(s2); ts.add(s3); for (Student s:ts){ System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getAge()+"\t"+s.getAddress()); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=50825:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.Comparable1 1 Yangyuhuan 28 XA 2 Diaochan 29 CA 3 Wangzhaojun 30 GD Process finished with exit code 0
package Java1; import java.util.Objects; public class StudentTest1 implements Comparable<StudentTest1> { private String name; public int age ; private String address; private String id; public StudentTest1(){} public StudentTest1(String name,int age,String address,String id){ this.name=name; this.id=id; this.address=address; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public int compareTo(StudentTest1 o) {//Compare the previous (added) elements in StudentTest1 int num = this.age-o.age; return num;//Sort according to whether the results are positive or negative } // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Student student = (Student) o; // return Objects.equals(name, student.name) && Objects.equals(age, student.age) && Objects.equals(address, student.address) && Objects.equals(id, student.id); // } @Override public int hashCode() { return Objects.hash(name, age, address, id); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=52499:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.Comparable1 Java1.StudentTest1@86c19525 4 Wangzhijun 24 GD Java1.StudentTest1@f2b8066e 1 Yangyuhuan 28 XA Java1.StudentTest1@2388c06d 2 Diaochan 29 CA Java1.StudentTest1@6e4b4f1 3 Wangzhaojun 30 GD Process finished with exit code 0
TreeSet() | Construct a new empty tree set and sort according to the natural order of elements. |
---|---|
TreeSet(Collection<? extends E> c) | Constructs a new tree set containing the elements in the specified set, and sorts its elements according to nature |
TreeSet(Comparator<? super E> comparator) | Sort the new set of comparators according to a new set of comparators. |
TreeSet(SortedSet<E> s) | Construct a new tree set that contains the same elements as the specified sort set and uses the same order |
package Java1; import java.util.Comparator; import java.util.TreeSet; public class TreeSetTest { public static void main(String[] args) { TreeSet<Student> treeSet=new TreeSet<Student>(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { int a=Integer.parseInt(o1.getAge()); int b=Integer.parseInt(o2.getAge()); int c=a-b; return c; } }); TreeSet<StudentTest1> ts= new TreeSet<StudentTest1>(); StudentTest1 s1 = new StudentTest1("Yangyuhuan",28,"XA","1"); StudentTest1 s2 =new StudentTest1("Diaochan",29,"CA","2"); StudentTest1 s3 = new StudentTest1("Wangzhaojun",30,"GD","3"); StudentTest1 s4 = new StudentTest1("Wangzhijun",24,"GD","4"); StudentTest1 s5 = new StudentTest1("Linqinxia",24,"GD","5"); ts.add(s1); ts.add(s2); ts.add(s3); ts.add(s4); ts.add(s5); for (StudentTest1 s:ts){ System.out.println(s); System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getAge()+"\t"+s.getAddress()); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=54121:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.TreeSetTest Java1.StudentTest1@86c19525 4 Wangzhijun 24 GD Java1.StudentTest1@f2b8066e 1 Yangyuhuan 28 XA Java1.StudentTest1@2388c06d 2 Diaochan 29 CA Java1.StudentTest1@6e4b4f1 3 Wangzhaojun 30 GD Process finished with exit code 0
package Java1; import java.util.Comparator; import java.util.TreeSet; public class TreeSetTest { public static void main(String[] args) { TreeSet<Student> treeSet=new TreeSet<Student>(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { int a=Integer.parseInt(o1.getAge()); int b=Integer.parseInt(o2.getAge()); // int a1=Integer.parseInt(o1.getName()); // int b1=Integer.parseInt(o2.getName()); int c=a-b; int num = c ==0 ? o1.getName().compareTo(o2.getName()):c; return num; } }); TreeSet<StudentTest1> ts= new TreeSet<StudentTest1>(); StudentTest1 s1 = new StudentTest1("Yangyuhuan",28,"XA","1"); StudentTest1 s2 =new StudentTest1("Diaochan",29,"CA","2"); StudentTest1 s3 = new StudentTest1("Wangzhaojun",30,"GD","3"); StudentTest1 s4 = new StudentTest1("Wangzhijun",24,"GD","4"); StudentTest1 s5 = new StudentTest1("Linqinxia",24,"GD","5"); ts.add(s1); ts.add(s2); ts.add(s3); ts.add(s4); ts.add(s5); for (StudentTest1 s:ts){ System.out.println(s); System.out.println(s.getId()+"\t"+s.getName()+"\t"+s.getAge()+"\t"+s.getAddress()); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=54325:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.TreeSetTest Java1.StudentTest1@ed5fac86 5 Linqinxia 24 GD Java1.StudentTest1@86c19525 4 Wangzhijun 24 GD Java1.StudentTest1@f2b8066e 1 Yangyuhuan 28 XA Java1.StudentTest1@2388c06d 2 Diaochan 29 CA Java1.StudentTest1@6e4b4f1 3 Wangzhaojun 30 GD Process finished with exit code 0
There are anonymous inner classes
Grade ranking
package Java1; import java.util.Comparator; import java.util.TreeSet; public class ScoreComparable { public static void main(String[] args) { TreeSet<ScoreTest1> treeSet=new TreeSet<ScoreTest1>(new Comparator<ScoreTest1>() { @Override public int compare(ScoreTest1 o1, ScoreTest1 o2) { // // double num=o2.getSum()-o1.getSum(); int num=Double.compare(o2.getSum(), o1.getSum())==0?o2.getName().compareTo(o1.getName()):Double.compare(o2.getSum(), o1.getSum()); return num ; } }); ScoreTest1 s1=new ScoreTest1(98.0,97,"X1"); ScoreTest1 s2=new ScoreTest1(96.0,97,"X2"); ScoreTest1 s3=new ScoreTest1(95.0,97,"X3"); ScoreTest1 s4=new ScoreTest1(95.0,99,"X4"); ScoreTest1 s5=new ScoreTest1(98.0,98,"X5"); ScoreTest1 s6=new ScoreTest1(98.0,97,"X6"); treeSet.add(s1); treeSet.add(s2); treeSet.add(s3); treeSet.add(s4); treeSet.add(s5); treeSet.add(s6); for (ScoreTest1 s:treeSet){ System.out.println(s.getName()+" "+s.getChinese()+""+s.getMath()+" "+s.getSum()); } } }
package Java1; public class ScoreTest1 { private double chinese; private double math; private String name; public ScoreTest1(double chinese, double math, String name) { this.chinese = chinese; this.math = math; this.name = name; } public void setChinese(double chinese) { this.chinese = chinese; } public void setMath(double math) { this.math = math; } public void setName(String name) { this.name = name; } public double getChinese() { return chinese; } public double getMath() { return math; } public String getName() { return name; } public double getSum(){ return chinese+math; } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=60766:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.ScoreComparable X5 98.098.0 196.0 X6 98.097.0 195.0 X1 98.097.0 195.0 X4 95.099.0 194.0 X2 96.097.0 193.0 X3 95.097.0 192.0 Process finished with exit code 0
Non repeating random number
package Java1; import java.util.Random; import java.util.TreeSet; public class RandomSet { public static void main(String[] args) { TreeSet<Integer> treeSet=new TreeSet<Integer>(); Random r=new Random(); while (treeSet.size()<10){ int rn=r.nextInt(20); treeSet.add(rn); } for (Integer i:treeSet){ System.out.println(i); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=61016:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.RandomSet 0 1 4 5 6 8 12 15 17 19 Process finished with exit code 0
generic paradigm
Generic class
package Java1a; public class Test1 { public static void main(String[] args) { NameText1 n=new NameText1("linqinxia"); System.out.println(n.getName()); AgeText1 a=new AgeText1(19); System.out.println(a.getAge()); System.out.println("=================="); GenericTest1<String> g1=new GenericTest1<String>("Yanlong"); GenericTest1<Integer> g2=new GenericTest1<Integer>(20); System.out.println(g1.getT()); System.out.println(g2.getT()); } }
package Java1a; public class AgeText1 { private int age; public AgeText1(int age) { this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
package Java1a; public class NameText1 { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public NameText1(String name) { this.name = name; } }
package Java1a; public class GenericTest1<T> { T t; public T getT() { return t; } public void setT(T t) { this.t = t; } public GenericTest1(T t) { this.t = t; } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=61795:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1a.Test1 linqinxia 19 ================== Yanlong 20 Process finished with exit code 0
generic method
package Java1a; public class Test1 { public static void main(String[] args) { NameText1 n=new NameText1("linqinxia"); System.out.println(n.getName()); AgeText1 a=new AgeText1(19); System.out.println(a.getAge()); System.out.println("=================="); GenericTest1<String> g1=new GenericTest1<String>("Yanlong"); GenericTest1<Integer> g2=new GenericTest1<Integer>(20); System.out.println(g1.getT()); System.out.println(g2.getT()); System.out.println("==================="); WayWideTest1 w=new WayWideTest1(); w.show("YunJi"); w.show(19); } }
package Java1a; public class WayWideTest1 { public<T> void show(T t){ System.out.println(t); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=62200:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1a.Test1 linqinxia 19 ================== Yanlong 20 =================== YunJi 19 Process finished with exit code 0
generic interface
package Java1a; public interface InterfaceWideTest1<T> { void show(T t); } class ImplementTest1<T> implements InterfaceWideTest1<T>{ @Override public void show(T t) { System.out.println(t); } } class Test1a{ public static void main(String[] args) { ImplementTest1<String> i=new ImplementTest1<String>(); i.show("Ye"); ImplementTest1<Integer> i2=new ImplementTest1<Integer>(); i2.show(19); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=62362:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1a.Test1a Ye 19 Process finished with exit code 0
Type wildcard
package Java1a; import java.util.ArrayList; import java.util.List; public class ClassChar { public static void main(String[] args) { List<?> list1=new ArrayList<Object>(); List<?> list2=new ArrayList<Number>(); List<?> list3=new ArrayList<Integer>(); List<?> list4=new ArrayList<String>(); List<?> list5=new ArrayList<Double>(); System.out.println("============="); //The upper limit is Number and Object is the parent of Number // List<? extends Number> list6=new ArrayList<Object>();error List<? extends Object> list7=new ArrayList<Number>(); System.out.println("=============="); //Similarly, to call a child, you need to create a parent object //List<? super Number> list8=new ArrayList<Integer>(); List<? super String> list9=new ArrayList<Object>(); } }
Variable parameter
package Java1; public class ChangeTest { public static void main(String[] args) { a(2);//From the execution result, a is an Int set System.out.println(a(1,23,2)); System.out.println(b(1,1,2,3,4,5)); } public static int a(int...a){ System.out.println(a); int sum=0; for (int i:a){ sum+=i; } return sum; } public static double b(double a,double...b){ //Multiple variable variable parameters can only be placed later double sum=0; for (double b1:b){ sum=b1*a; } return sum; } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=64092:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.ChangeTest [I@1d251891 [I@48140564 26 5.0 Process finished with exit code 0
Use of variable parameters
Map
package Java1; import java.util.HashMap; import java.util.Map; public class MapTest1 { public static void main(String[] args) { Map<String,String> map=new HashMap<String,String>(); map.put("001","wangjiawei"); map.put("002","zouxinchi"); map.put("003","linzhexu"); map.put("003","linz");//To ensure uniqueness, the value will be overwritten‘ System.out.println(map); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=64378:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.MapTest1 {001=wangjiawei, 002=zouxinchi, 003=linz} Process finished with exit code 0
Acquisition of Map set value
package Java1; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; public class MapCollectTest1 { public static void main(String[] args) { Map<String,String> map=new HashMap<String,String>(); map.put("001","Lx"); map.put("002","Xz"); map.put("003","Hdq"); System.out.println(map.get("001")); Set<String> set=map.keySet(); for (String s:set){ System.out.println(s); } Collection<String> set1=map.values(); for (String s:set1){ System.out.println(s); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=64675:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.MapCollectTest1 Lx 001 002 003 Lx Xz Hdq Process finished with exit code 0
Traversal of Map collection
package Java1a; import java.util.HashMap; import java.util.Map; import java.util.Set; public class MapSetTest1 { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("001", "Zhang San"); map.put("002", "Li Si"); map.put("003", "Wang Wu"); Set<Map.Entry<String, String>> entrySet = map.entrySet(); for (Map.Entry<String,String> s:entrySet){ System.out.println(s.getKey()+" "+s.getValue()); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=50076:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1a.MapSetTest1 001 Zhang San 002 Li Si 003 Wang Wu Process finished with exit code 0
HashMap
package Java1a; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class HashMapStudent1 { public static void main(String[] args) { HashMap<String,NameAndAge> hashMap=new HashMap<String,NameAndAge>(); NameAndAge lin = new NameAndAge("Lin", 35); NameAndAge Ye = new NameAndAge("ye", 30); NameAndAge Hua = new NameAndAge("Hua", 33); hashMap.put("001",lin); hashMap.put("002",Ye); hashMap.put("003",Hua); Set<String> s=hashMap.keySet(); for (String e:s){ System.out.println(e+" "+hashMap.get(e).getName()+" "+hashMap.get(e).getAge()); //Find value by key } System.out.println("=================="); Set<Map.Entry<String, NameAndAge>> entries = hashMap.entrySet(); for (Map.Entry<String,NameAndAge> q:entries){ System.out.println(q.getKey()+" "+q.getValue().getName()+" "+q.getValue().getAge()); } } }
package Java1a; public class NameAndAge { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public NameAndAge(String name, int age) { this.name = name; this.age = age; } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=50360:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1a.HashMapStudent1 001 Lin 35 002 ye 30 003 Hua 33 ================== 001 Lin 35 002 ye 30 003 Hua 33 Process finished with exit code 0
package Java1a; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class HashMapStudent1 { public static void main(String[] args) { HashMap<String,NameAndAge> hashMap=new HashMap<String,NameAndAge>(); NameAndAge lin = new NameAndAge("Lin", 35); NameAndAge Ye = new NameAndAge("ye", 30); NameAndAge Hua = new NameAndAge("Hua", 33); hashMap.put("001",lin); hashMap.put("002",Ye); hashMap.put("003",Hua); hashMap.put("003",Hua); Set<String> s=hashMap.keySet(); for (String e:s){ System.out.println(e+" "+hashMap.get(e).getName()+" "+hashMap.get(e).getAge()); //Find value by key } System.out.println("=================="); Set<Map.Entry<String, NameAndAge>> entries = hashMap.entrySet(); for (Map.Entry<String,NameAndAge> q:entries){ System.out.println(q.getKey()+" "+q.getValue().getName()+" "+q.getValue().getAge()); } } }
hashCode uniqueness (NameAndAge class)
package Java1a; public class NameAndAge { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public NameAndAge(String name, int age) { this.name = name; this.age = age; } }
package Java1a; import java.util.HashMap; import java.util.Map; import java.util.Set; public class HashMapStudent2 { public static void main(String[] args) { HashMap<NameAndAge,String> hashMap=new HashMap<NameAndAge,String>(); NameAndAge lin = new NameAndAge("Lin", 35); NameAndAge Ye = new NameAndAge("ye", 30); NameAndAge Hua = new NameAndAge("Hua", 33); NameAndAge Hua2 = new NameAndAge("Hua", 33); hashMap.put(lin,"Gd"); hashMap.put(Hua,"Bj"); hashMap.put(Hua2,"Bj"); hashMap.put(Ye,"Fj");//To ensure the uniqueness of key values, you need to override the equal and hashCode methods (the String class comes with it, so you don't need to override it) Set<Map.Entry<NameAndAge, String>> entries = hashMap.entrySet(); for (Map.Entry<NameAndAge,String> s:entries){ System.out.println(s.getKey().getName()+" "+s.getKey().getAge()+" "+s.getValue()); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=51119:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1a.HashMapStudent2 Lin 35 Gd ye 30 Fj Hua 33 Bj Hua 33 Bj Process finished with exit code 0
compare
package Java1a; import java.util.HashMap; import java.util.Map; import java.util.Set; public class HashMapStudent2 { public static void main(String[] args) { HashMap<NameAndAge,String> hashMap=new HashMap<NameAndAge,String>(); NameAndAge lin = new NameAndAge("Lin", 35); NameAndAge Ye = new NameAndAge("ye", 30); NameAndAge Hua = new NameAndAge("Hua", 33); NameAndAge Hua2 = new NameAndAge("Hua", 33); hashMap.put(lin,"Gd"); hashMap.put(Hua,"Bj"); hashMap.put(Hua2,"Bj"); hashMap.put(Ye,"Fj");//To ensure the uniqueness of key values, you need to override the equal and hashCode methods (the String class comes with it, so you don't need to override it) Set<Map.Entry<NameAndAge, String>> entries = hashMap.entrySet(); for (Map.Entry<NameAndAge,String> s:entries){ System.out.println(s.getKey().getName()+" "+s.getKey().getAge()+" "+s.getValue()); } } }
package Java1a; import java.util.Objects; public class NameAndAge { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NameAndAge that = (NameAndAge) o; return age == that.age && Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(name, age); } public NameAndAge(String name, int age) { this.name = name; this.age = age; } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=51143:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1a.HashMapStudent2 ye 30 Fj Lin 35 Gd Hua 33 Bj Process finished with exit code 0
Case ---- add HashMap element in arrayList set
package Java1a; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; public class ArrayListAboutMap1 { public static void main(String[] args) { ArrayList<HashMap<String,String>> arrayList=new ArrayList<HashMap<String,String>>(); HashMap<String,String> m1=new HashMap<String,String>(); HashMap<String,String> m2=new HashMap<String,String>(); HashMap<String,String> m3=new HashMap<String,String>(); m1.put("001","Wang Zuxian"); m1.put("002","Lin Qingxia"); m2.put("001","linghu chong"); m2.put("002","invincible eastern"); m3.put("001","Lord Lao Zi"); m3.put("002","Qi Tian Da Sheng"); arrayList.add(m1); arrayList.add(m2); arrayList.add(m3); for (HashMap<String,String> s:arrayList){ Set<String> set=s.keySet();//s.keySet() is a set for (String s1:set){ System.out.println(s1+" "+s.get(s1)); } } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=52376:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1a.ArrayListAboutMap1 001 Wang Zuxian 002 Lin Qingxia 001 linghu chong 002 invincible eastern 001 Lord Lao Zi 002 Qi Tian Da Sheng Process finished with exit code 0
Case ---- add arrayList to HashMap set
package Java1a; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; public class HashMapAboutArrayList1 { public static void main(String[] args) { HashMap<String, ArrayList<String>> hashMap=new HashMap<String,ArrayList<String>>(); ArrayList<String> a1 = new ArrayList<String>(); ArrayList<String> a2 = new ArrayList<String>(); ArrayList<String> a3 = new ArrayList<String>(); a1.add("Qi Tian Da Sheng"); a1.add("Marshal Tianpeng"); a2.add("Lin Chong"); a2.add("Wu Song"); a3.add("Jia Baoyu"); a3.add("Lin Daiyu"); hashMap.put("Journey to the West",a1); hashMap.put("Water Margin",a2); hashMap.put("The Dream of Red Mansion",a3); for (String s: hashMap.keySet()){ ArrayList<String> value=hashMap.get(s); System.out.println(s); for (String s1:value){ System.out.println("\t"+s1); } } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=55060:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1a.HashMapAboutArrayList1 Water Margin Lin Chong Wu Song The Dream of Red Mansion Jia Baoyu Lin Daiyu Journey to the West Qi Tian Da Sheng Marshal Tianpeng Process finished with exit code 0
Counts the number of occurrences of each character in a string
package Java1; import java.util.HashMap; import java.util.Scanner; public class CharNumber { public static void main(String[] args) { System.out.println("Please input a String"); Scanner scanner=new Scanner(System.in); String s=scanner.nextLine(); HashMap<Character,Integer> hashMap=new HashMap<Character,Integer>(); for (int i=0;i<s.length();i++){ char c=s.charAt(i);//get every chars Integer integer=hashMap.get(c); if (integer == null) {//This is null of number hashMap.put(c,1); }else { integer++; hashMap.put(c,integer); } } // System.out.println(hashMap.size()); for (Character c:hashMap.keySet()){ // System.out.println(c); System.out.println(c+"("+hashMap.get(c)+")"); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=56198:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.CharNumber Please input a String abcdeefghijklnn a(1) b(1) c(1) d(1) e(2) f(1) g(1) h(1) i(1) j(1) k(1) l(1) n(2) Process finished with exit code 0
package Java1; import java.util.HashMap; import java.util.Scanner; import java.util.TreeMap; public class CharNumber { public static void main(String[] args) { System.out.println("Please input a String"); Scanner scanner=new Scanner(System.in); String s=scanner.nextLine(); TreeMap<Character,Integer> hashMap=new TreeMap<Character,Integer>();//The keys are arranged in order for (int i=0;i<s.length();i++){ char c=s.charAt(i);//get every chars Integer integer=hashMap.get(c); if (integer == null) {//This is null of number hashMap.put(c,1); }else { integer++; hashMap.put(c,integer); } } // System.out.println(hashMap.size()); for (Character c:hashMap.keySet()){ // System.out.println(c); System.out.println(c+"("+hashMap.get(c)+")"); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=56329:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.CharNumber Please input a String adknnvzdfanyzm a(2) d(2) f(1) k(1) m(1) n(3) v(1) y(1) z(2) Process finished with exit code 0
Collections overview and usage
package Java1; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class CollectionTest1 { public static void main(String[] args) { List<Integer> list=new ArrayList<Integer>(); list.add(30); list.add(10); list.add(20); list.add(70); list.add(90); list.add(33); list.add(38); System.out.println(list); System.out.println("=============="); Collections.sort(list);//Collection sorting method System.out.println(list); System.out.println("=============="); Collections.reverse(list);//Collection reverse order method System.out.println(list); System.out.println("=================="); Collections.shuffle(list);//Random sorting System.out.println(list); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=56728:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.CollectionTest1 [30, 10, 20, 70, 90, 33, 38] ============== [10, 20, 30, 33, 38, 70, 90] ============== [90, 70, 38, 33, 30, 20, 10] ================== [30, 10, 70, 38, 90, 20, 33] Process finished with exit code 0
Case ---- ArrayList stores student objects and traverses them
package Java1; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class ArrayListAboutStudent { public static void main(String[] args) { ArrayList<NameAndAge> arrayList=new ArrayList<NameAndAge>(); NameAndAge na1 = new NameAndAge("Zhang Sanfeng", 19); NameAndAge na2 = new NameAndAge("Li Si", 32); NameAndAge na3 = new NameAndAge("Wang Wu", 24); NameAndAge na4 = new NameAndAge("Old six", 42); arrayList.add(na1); arrayList.add(na2); arrayList.add(na3); arrayList.add(na4); //Anonymous inner class comparison method Collections.sort(arrayList, new Comparator<NameAndAge>() { @Override public int compare(NameAndAge o1, NameAndAge o2) { int num1= o2.getAge()-o1.getAge(); int num2=num1==0?o2.getName().compareTo(o1.getName()):num1; return num2; } }); for (NameAndAge nameAndAge:arrayList){ System.out.println(nameAndAge.getName()+" "+nameAndAge.getAge()); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=57604:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.ArrayListAboutStudent Old six 42 Li Si 32 Wang wu24 Zhang Sanfeng 19 Process finished with exit code 0
Case simulation landlords
package Java1; import java.util.ArrayList; import java.util.Collections; public class PockerTest1 { public static void main(String[] args) { ArrayList<String> arrayList=new ArrayList<String>(); String[] color={"♦","♠","♥","♣"}; String[] number={"A","2","3","4","5","6","7","8","9","10","J","Q","K"}; for (int i=0;i<color.length;i++){ for (int n=0;n<number.length;n++){ arrayList.add(color[i]+number[n]); } } arrayList.add("king"); arrayList.add("Xiao Wang"); System.out.println(arrayList); System.out.println("===================="); //user ArrayList<String> lqx=new ArrayList<String>(); ArrayList<String> ly=new ArrayList<String>(); ArrayList<String> fqy=new ArrayList<String>(); ArrayList<String> dp=new ArrayList<String>(); Collections.shuffle(arrayList); for (int i=0;i<arrayList.size();i++){ // Get cards if (i>=arrayList.size()-3){ dp.add(arrayList.get(i)); } if (i%3==0){ lqx.add(arrayList.get(i)); }else if (i%3==1){ ly.add(arrayList.get(i)); }else if (i%3==2){ fqy.add(arrayList.get(i)); } } System.out.println("Zero brand new"+"t"+lqx); System.out.println("June"+"t"+ly); System.out.println("Breezy"+"t"+fqy); System.out.println("a hand"+"t"+dp); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=58396:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.PockerTest1 [♦A, ♦2, ♦3, ♦4, ♦5, ♦6, ♦7, ♦8, ♦9, ♦10, ♦J, ♦Q, ♦K, ♠A, ♠2, ♠3, ♠4, ♠5, ♠6, ♠7, ♠8, ♠9, ♠10, ♠J, ♠Q, ♠K, ♥A, ♥2, ♥3, ♥4, ♥5, ♥6, ♥7, ♥8, ♥9, ♥10, ♥J, ♥Q, ♥K, ♣A, ♣2, ♣3, ♣4, ♣5, ♣6, ♣7, ♣8, ♣9, ♣10, ♣J, ♣Q, ♣K, king, Xiao Wang] ==================== Zero brand new t[♦K, ♣10, ♦6, ♦8, ♠5, ♥Q, ♣3, ♣7, ♥5, ♥6, ♠3, ♦J, ♦10, ♣A, ♠Q, ♦7, ♥2, ♠10] June t[♦2, ♣6, ♠K, ♠6, ♦Q, ♥9, ♠7, ♠8, ♥10, ♥3, ♣9, ♠4, ♣Q, ♣K, ♣5, ♠2, ♦5, king] Breezy t[♣J, ♥8, ♦A, ♦9, ♠A, ♣4, ♠9, ♥4, ♣8, ♥A, ♦4, ♠J, ♥7, ♥J, ♥K, Xiao Wang, ♣2, ♦3] a hand t[♠10, king, ♦3] Process finished with exit code 0
Simulated landlords upgrade
IO stream
File class overview and construction method
package FileDemo1; import java.io.File; public class FileTest1 { public static void main(String[] args) { File file=new File("E:\\FileJava\\java.txt"); System.out.println(file); File file1=new File("E:\\FileJava","java.txt"); System.out.println(file1); File file2=new File("E:\\FileJava"); File file3=new File(file2,"java.txt"); System.out.println(file3); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=59242:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava FileDemo1.FileTest1 E:\FileJava\java.txt E:\FileJava\java.txt E:\FileJava\java.txt Process finished with exit code 0
File class creation function
package FileDemo1; import java.io.File; import java.io.IOException; public class FileTest2 { public static void main(String[] args) throws IOException { //Create a file without a file and return a true value //If there is a file, the file is not created and a false is returned File f1=new File("D:\\FileJava"); System.out.println(f1.createNewFile()); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=59337:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava FileDemo1.FileTest2 true Process finished with exit code 0
/After creation
package FileDemo1; import java.io.File; import java.io.IOException; public class FileTest2 { public static void main(String[] args) throws IOException { //Create a file without a file and return a true value //If there is a file, the file is not created and a false is returned File f1=new File("D:\\FileJava"); System.out.println(f1.createNewFile()); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=59364:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava FileDemo1.FileTest2 false Process finished with exit code 0
package FileDemo1; import java.io.File; import java.io.IOException; public class FileTest2 { public static void main(String[] args) throws IOException { //Create a file without a file and return a true value //If there is a file, the file is not created and a false is returned File f1=new File("D:\\FileJava"); System.out.println(f1.createNewFile()); //Create a new directory under a directory //Create a directory without a directory (folder) and return a true value //If there is a directory, the directory will not be created and a false will be returned File f2=new File("D:\\cTd download\\JavaFile"); System.out.println(f2.mkdir()); // File f3=new File("D:\cTd download Test"); // System.out.println(f2.mkdir()); //Create a multi-level directory //Create multiple new directories under one directory //Create a directory without a directory (folder) and return a true value //If there is a directory, the directory will not be created and a false will be returned File f3=new File("D:\\cTd download\\Java\\Wed"); System.out.println(f3.mkdirs()); //Note that you cannot judge whether a directory or a file is created by the address alone. It depends on the method called //Note that if a file with the same name already exists in a directory, creating a directory with the same name in this directory will be false File f4=new File("D:\\cTd download\\Java"); System.out.println(f4.createNewFile()); //Note that if a directory with the same name already exists in a directory, creating a file with the same name in this directory will also be false File f5=new File("D:\\cTd download\\JavaContent"); System.out.println(f5.createNewFile()); File f6=new File("D:\\cTd download\\JavaContent"); System.out.println(f6.mkdir()); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=51015:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava FileDemo1.FileTest2 false false false false true false Process finished with exit code 0
File class judgment and acquisition function
package FileDemo1; import java.io.File; import java.io.IOException; public class FileTest3 { public static void main(String[] args) throws IOException { //MyFile file under heimaJava folder File f2=new File("MyFile"); System.out.println(f2.exists()); System.out.println(f2.isFile()); System.out.println(f2.isDirectory()); System.out.println(f2.isAbsolute()); System.out.println(f2.getAbsoluteFile()); System.out.println(f2.getPath()); System.out.println(f2.getName()); System.out.println("==============="); File f3=new File("D:\\heimaJava"); //Is an array object, so it needs to be traversed System.out.println(f3.list()); String[] strings=f3.list(); for (String s:strings){ System.out.println(s); } System.out.println("=============="); File[] files=f3.listFiles();//An array of File type can be imagined as containing File elements (the absolute addresses of all files under the object) for (File s:files){ System.out.println(s); } System.out.println("========="); for (File s:files){ System.out.println(s.getName()); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=52265:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava FileDemo1.FileTest3 true false true false D:\heimaJava\MyFile MyFile MyFile =============== [Ljava.lang.String;@1d251891 .idea heimaJava.iml MyFile out src ============== D:\heimaJava\.idea D:\heimaJava\heimaJava.iml D:\heimaJava\MyFile D:\heimaJava\out D:\heimaJava\src ========= .idea heimaJava.iml MyFile out src Process finished with exit code 0
File class deletion function
package FileDemo1; import java.io.File; import java.io.IOException; public class FileTest4 { public static void main(String[] args) throws IOException { File f1=new File("FileDelete"); System.out.println(f1.mkdir()); File f2=new File("FileDelete\\fileDelete.txt"); System.out.println(f2.createNewFile()); //Note that you can only delete an empty directory, otherwise you need to empty the directory first and then delete it // System.out.println(f1.delete());false System.out.println(f2.delete()); System.out.println(f1.delete()); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=52830:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava FileDemo1.FileTest4 false false true true Process finished with exit code 0
package FileDemo1; import java.io.File; public class FileArrayRecursion { public static void main(String[] args) { File file=new File("D:\\Data communication and network"); RecursionAll(file); } public static void RecursionAll(File f){ File[] files=f.listFiles(); //if (files != null) for (File file:files) { if (file.isDirectory()) { RecursionAll(file); }else { System.out.println(file.getAbsoluteFile()); } } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=51018:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava FileDemo1.FileArrayRecursion D:\Data communication and network\1 Browse Chapter 1.rar D:\Data communication and network\1 Browse Chapter 1.wmv D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\01.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\02.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\03.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\04.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\05.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\06.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\07.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\08.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\09.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\computer network.png D:\Data communication and network\2 Read Chapter 1.rar D:\Data communication and network\2 Read Chapter 1.wmv D:\Data communication and network\3 Practice Chapter 1.wmv D:\Data communication and network\3 Practice Chapter 1.zip D:\Data communication and network\eNSP V100R002C00B510 Setup.exe D:\Data communication and network\eNSP V100R002C00B510 Setup.rar D:\Data communication and network\Guide to Networking Essentials(7th).pdf D:\Data communication and network\Experiment 1-4 Switch configuration.docx D:\Data communication and network\data communication\data communication\AR120, AR150, AR160, AR200, AR1200, AR2200, AR320\AR120, AR150, AR160, AR200, AR1200, AR2200, AR3200, AR3600 V200R007 Product documentation.chm D:\Data communication and network\data communication\data communication\AR120, AR150, AR160, AR200, AR1200, AR2200, AR320.zip D:\Data communication and network\data communication\data communication\eNSP V100R002C00B510 Setup.zip D:\Data communication and network\data communication\data communication\Guide to Networking Essentials(7th).pdf D:\Data communication and network\data communication\data communication\PacketTracer70_64bit_setup.exe D:\Data communication and network\data communication\data communication\PacketTracer71_64bit_setup_signed.exe D:\Data communication and network\data communication\data communication\S2750, S5700, S6700 V200R005(C00&C01&C02&C03) Product text\S2750, S5700, S6700 V200R005(C00&C01&C02&C03) Product documentation.chm D:\Data communication and network\data communication\data communication\S2750, S5700, S6700 V200R005(C00&C01&C02&C03) Product text.zip D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 1\ICT106-T119-L1-SS-07MAR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 1\ICT106-T219-T1-10JUL2019.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 2\ICT106-T119-L2-14MAR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 2\ICT106-T318-T2-14MAR2019.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 3\ICT106-T119-L3-SS-19MAR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 3\ICT106-T119-T3-SS-19MAR2019.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 4\ICT106-T119-L4-SS-22MAR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 4\ICT106-T119-PracticeQuestions-L4.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 4\ICT106-T119-T4-SS-22MAR2019.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 5\ICT106-T119-L5-SS-22MAR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 5\ICT106-T318-L5-SS-03DEC2018.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 5\ICT106-T318-Mid-Trimester-Revision1.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 5\ICT106-T318-PracticeQuestions-L5.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 5\ICT106-T318-T5-SS-10OCT2018.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 6\ICT106-T119-L6-SS-22MAR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 6\ICT106-T119-T6-SS-13APR2019.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 7\ICT106-T119-L7-SS-23APR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 7\ICT106-T119-T7-SS-23APR2019.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 8\ICT106-T119-L8-SS-23APR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 8\ICT106-T119-T8-SS-23APR2019.docx D:\Data communication and network\data communication\data communication\King's College PPT.zip D:\Data communication and network\data communication.zip Process finished with exit code 0
person first
package FileDemo1; import java.io.File; public class FileArrayRecursion { public static void main(String[] args) { File file = new File("D:\\Data communication and network"); RecursionAll(file); } public static void RecursionAll(File f) { File[] files = f.listFiles(); for (File file : files) { if (file.isDirectory()) { if (file.listFiles() != null) { RecursionAll(file); } } else { System.out.println(file.getAbsoluteFile()); } } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=51079:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava FileDemo1.FileArrayRecursion D:\Data communication and network\1 Browse Chapter 1.rar D:\Data communication and network\1 Browse Chapter 1.wmv D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\01.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\02.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\03.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\04.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\05.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\06.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\07.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\08.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\09.pptx D:\Data communication and network\2\Xie Xiren computer network Seventh Edition PowerPoint\computer network.png D:\Data communication and network\2 Read Chapter 1.rar D:\Data communication and network\2 Read Chapter 1.wmv D:\Data communication and network\3 Practice Chapter 1.wmv D:\Data communication and network\3 Practice Chapter 1.zip D:\Data communication and network\eNSP V100R002C00B510 Setup.exe D:\Data communication and network\eNSP V100R002C00B510 Setup.rar D:\Data communication and network\Guide to Networking Essentials(7th).pdf D:\Data communication and network\Experiment 1-4 Switch configuration.docx D:\Data communication and network\data communication\data communication\AR120, AR150, AR160, AR200, AR1200, AR2200, AR320\AR120, AR150, AR160, AR200, AR1200, AR2200, AR3200, AR3600 V200R007 Product documentation.chm D:\Data communication and network\data communication\data communication\AR120, AR150, AR160, AR200, AR1200, AR2200, AR320.zip D:\Data communication and network\data communication\data communication\eNSP V100R002C00B510 Setup.zip D:\Data communication and network\data communication\data communication\Guide to Networking Essentials(7th).pdf D:\Data communication and network\data communication\data communication\PacketTracer70_64bit_setup.exe D:\Data communication and network\data communication\data communication\PacketTracer71_64bit_setup_signed.exe D:\Data communication and network\data communication\data communication\S2750, S5700, S6700 V200R005(C00&C01&C02&C03) Product text\S2750, S5700, S6700 V200R005(C00&C01&C02&C03) Product documentation.chm D:\Data communication and network\data communication\data communication\S2750, S5700, S6700 V200R005(C00&C01&C02&C03) Product text.zip D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 1\ICT106-T119-L1-SS-07MAR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 1\ICT106-T219-T1-10JUL2019.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 2\ICT106-T119-L2-14MAR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 2\ICT106-T318-T2-14MAR2019.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 3\ICT106-T119-L3-SS-19MAR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 3\ICT106-T119-T3-SS-19MAR2019.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 4\ICT106-T119-L4-SS-22MAR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 4\ICT106-T119-PracticeQuestions-L4.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 4\ICT106-T119-T4-SS-22MAR2019.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 5\ICT106-T119-L5-SS-22MAR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 5\ICT106-T318-L5-SS-03DEC2018.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 5\ICT106-T318-Mid-Trimester-Revision1.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 5\ICT106-T318-PracticeQuestions-L5.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 5\ICT106-T318-T5-SS-10OCT2018.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 6\ICT106-T119-L6-SS-22MAR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 6\ICT106-T119-T6-SS-13APR2019.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 7\ICT106-T119-L7-SS-23APR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 7\ICT106-T119-T7-SS-23APR2019.docx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 8\ICT106-T119-L8-SS-23APR2019.pptx D:\Data communication and network\data communication\data communication\King's College PPT\WEEK 8\ICT106-T119-T8-SS-23APR2019.docx D:\Data communication and network\data communication\data communication\King's College PPT.zip D:\Data communication and network\data communication.zip Process finished with exit code 0
Byte stream
IO stream overview and classification
Byte stream write data
package OutStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class OutStreamTest1 { public static void main(String[] args) throws IOException { FileOutputStream file=new FileOutputStream("D:\\heimaJava\\outputEdit.txt"); /*Three things were done: 1.Call system functions to create files 2.Created byte output stream object 3.Let the byte output stream object point to the created file */ //Write the specified character file.write(64); file.write(92); file.write(57); //Close this file output stream and free up any system resources associated with this stream file.close(); } }
Three ways to write data in byte stream
package OutStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class OutStream { public static void main(String[] args) throws IOException { File file=new File("OutStreamTest2"); FileOutputStream fileOutputStream=new FileOutputStream(file); fileOutputStream.write(97); fileOutputStream.write(98); fileOutputStream.write(99); byte[] bytes={97,98,99}; fileOutputStream.write(bytes); byte[] bytes1="Bing Bing Wang".getBytes(); fileOutputStream.write(bytes1,0, bytes1.length);//Start and end of array } }
/Forget close
package OutStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class OutStream { public static void main(String[] args) throws IOException { File file=new File("OutStreamTest2"); FileOutputStream fileOutputStream=new FileOutputStream(file); fileOutputStream.write(97); fileOutputStream.write(98); fileOutputStream.write(99); byte[] bytes={97,98,99}; fileOutputStream.write(bytes); byte[] bytes1="Bing Bing Wang".getBytes(); fileOutputStream.write(bytes1,0, bytes1.length);//Start and end of array fileOutputStream.close(); } }
Two small problems in writing data in byte stream
package OutStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class OutputStreamTest1 { public static void main(String[] args) throws IOException { FileOutputStream fileOutputStream = new FileOutputStream("OutputStream", true); byte[] bytes = "linghu chong".getBytes(); for (int i = 0; i < bytes.length; i++) { fileOutputStream.write(bytes); fileOutputStream.write("\r\n".getBytes()); } fileOutputStream.close(); } }
exception handling
Byte stream read data
package InputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class InputTest1 { public static void main(String[] args) throws IOException { FileInputStream fileInputStream=new FileInputStream("outputEdit.txt"); int read1 = fileInputStream.read(); System.out.println(read1); System.out.println((char) read1); int read2 = fileInputStream.read(); System.out.println(read2); System.out.println((char) read2); //-1 indicates the end of the read /* 1.read = fileInputStream.read() 2.(read = fileInputStream.read()) != -1 3.while ((read = fileInputStream.read()) != -1) 4.(char)read//This is equivalent to calling the read method Similar to recursion */ int read; while ((read = fileInputStream.read()) != -1) { System.out.print((char)read); } fileInputStream.close(); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=51663:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava InputStream.InputTest1 64 @ 92 \ 9 Hello world Process finished with exit code 0
Copy text file
package InputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class FileCope { public static void main(String[] args) throws IOException { //Create an input stream (input source) object FileInputStream fileInputStream=new FileInputStream("inputObject.txt"); //Create an output stream (source) object FileOutputStream fileOutputStream=new FileOutputStream("pasteObject.txt"); int read; //Read and write while ((read=fileInputStream.read()) !=-1){ fileOutputStream.write(read()); //Do not write fileoutputstream write(fileInputStream.read()); //Forget to close resources } } }
Byte stream reads byte array data
package InputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class readArraybyte { public static void main(String[] args) throws IOException { FileInputStream fileInputStream=new FileInputStream("inputObject.txt"); byte[] bytes=new byte[6]; int b=fileInputStream.read(bytes); //First read //b represents the length of the array read (once) System.out.println(b); //String(byte[] bytes) decodes the specified byte array by using the default character set of the platform to construct a new string System.out.println(new String(bytes)); System.out.println("============================"); //Second reading b=fileInputStream.read(bytes); System.out.println(b); System.out.println(new String(bytes)); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=52440:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava InputStream.readArraybyte 6 abcdef 6 g 1.a Process finished with exit code 0
package InputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class readArraybyte { public static void main(String[] args) throws IOException { FileInputStream fileInputStream=new FileInputStream("inputObject2.txt"); byte[] bytes=new byte[3]; int b=fileInputStream.read(bytes); //First read //b represents the length of the array read (once) System.out.println(b); //String(byte[] bytes) decodes the specified byte array by using the default character set of the platform to construct a new string System.out.println(new String(bytes)); System.out.println("============================"); //Second reading b=fileInputStream.read(bytes); System.out.println(b); System.out.println(new String(bytes)); //Third reading b=fileInputStream.read(bytes); System.out.println(b);//There's only one element left to read, so it's 1 System.out.println(new String(bytes)); //This is equivalent to rewriting the previous array //Since only the first element of the previous array is rewritten, the second and third array elements retain the original value of the previous array //So it's 756 } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=52559:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava InputStream.readArraybyte 3 123 ============================ 3 456 1 756 Process finished with exit code 0
1024
package InputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class readArraybyte { public static void main(String[] args) throws IOException { FileInputStream fileInputStream=new FileInputStream("inputObject2.txt"); byte[] bytes=new byte[1024]; int b=fileInputStream.read(bytes); //First read //b represents the length of the array read (once) System.out.println(b); //String(byte[] bytes) decodes the specified byte array by using the default character set of the platform to construct a new string System.out.println(new String(bytes)); //System.out.println( fileInputStream.read(bytes,0,2)); System.out.println("============================"); //Second reading b=fileInputStream.read(bytes); System.out.println(b); System.out.println(new String(bytes)); //Third reading b=fileInputStream.read(bytes); System.out.println(b);//There's only one element left to read, so it's 1 System.out.println(new String(bytes)); //This is equivalent to rewriting the previous array //Since only the first element of the previous array is rewritten, the second and third array elements retain the original value of the previous array //So it's 756 } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=53637:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava InputStream.readArraybyte 7 1234567 ============================ -1 1234567 -1 1234567 Process finished with exit code 0
Case ----------- copy pictures
package InputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class CopeImage { public static void main(String[] args) throws IOException { FileInputStream fileInputStream=new FileInputStream("Lenovo.jpeg"); FileOutputStream fileOutputStream=new FileOutputStream("PasteLenovo.jpeg"); byte[] bytes=new byte[1024]; int read; while ((read=fileInputStream.read(bytes))!=-1) { fileOutputStream.write(bytes,0,read); } fileInputStream.close(); fileOutputStream.close(); } }
Byte buffer stream
package InputStream; import java.io.*; public class BufferStream { public static void main(String[] args) throws IOException { FileOutputStream fileOutputStream=new FileOutputStream("paste2Object.txt"); FileInputStream fileInputStream=new FileInputStream("inputObject2.txt"); BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(fileOutputStream); BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream); byte[] bytes=new byte[1024]; int read; while ((read=bufferedInputStream.read(bytes))!=-1){ System.out.println(new String(bytes,0,read)); } fileInputStream.close(); fileOutputStream.close(); bufferedInputStream.close(); bufferedOutputStream.close(); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=55516:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava InputStream.BufferStream 1234567 Process finished with exit code 0
package InputStream; import java.io.*; public class BufferStream { public static void main(String[] args) throws IOException { BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream("paste2Object.txt")); BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream("inputObject.txt")); byte[] bytes=new byte[1024]; int read; while ((read=bufferedInputStream.read(bytes))!=-1){ System.out.println(new String(bytes,0,read)); bufferedOutputStream.write(bytes,0,read); } bufferedInputStream.close(); bufferedOutputStream.close(); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=56473:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava InputStream.BufferStream Hello World Process finished with exit code 0
Case copy video comparison buffer stream and ordinary, array and single transmission rate comparison
package InputStream; import java.io.*; /* method1 It takes 999999 (too many) ms in total method2 Total time: 5264ms(array) method3 It takes 15821ms in total method4 It takes 1050ms in total (array) */ public class BufferedCompareCommon { public static void main(String[] args) throws IOException { //Record start time long startTime=System.currentTimeMillis(); method2(); //Record end time long endTime=System.currentTimeMillis(); System.out.println("Total time"+(endTime-startTime)+"ms"); } public static void method3() throws IOException { BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream("video.mp4")); BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream("pasteVideo.mp4")); int read; while ((read=bufferedInputStream.read())!=-1){ bufferedOutputStream.write(read); } bufferedInputStream.close(); bufferedOutputStream.close(); } public static void method4() throws IOException { BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream("video.mp4")); BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream("pasteVideo.mp4")); int read; byte[] bytes=new byte[1024]; while ((read=bufferedInputStream.read(bytes))!=-1){ bufferedOutputStream.write(bytes,0,read); } bufferedInputStream.close(); bufferedOutputStream.close(); } public static void method2() throws IOException { FileInputStream bufferedInputStream=new FileInputStream("video.mp4"); FileOutputStream bufferedOutputStream=new FileOutputStream("pasteVideo.mp4"); int read; byte[] bytes=new byte[1024]; while ((read=bufferedInputStream.read(bytes))!=-1){ bufferedOutputStream.write(bytes,0,read); } bufferedInputStream.close(); bufferedOutputStream.close(); } public static void method1() throws IOException { FileInputStream bufferedInputStream=new FileInputStream("video.mp4"); FileOutputStream bufferedOutputStream=new FileOutputStream("pasteVideo.mp4"); int read; while ((read=bufferedInputStream.read())!=-1){ bufferedOutputStream.write(read); } bufferedInputStream.close(); bufferedOutputStream.close(); } }
Character stream
package Char; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class Test1 {//abc public static void main(String[] args) throws IOException { FileInputStream fileInputStream=new FileInputStream("charTest.txt"); int len; while((len=fileInputStream.read())!=-1){ System.out.print( len+":"); System.out.println((char) len); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=60525:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Char.Test1 97:a 98:b 99:c Process finished with exit code 0
package Char; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class Test1 {//China UTF-8 public static void main(String[] args) throws IOException { FileInputStream fileInputStream=new FileInputStream("charTest.txt"); int len; while((len=fileInputStream.read())!=-1){ System.out.print( len+":"); System.out.println((char) len); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=60580:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Char.Test1 228:ä 184:¸ 173: 229:å 155:› 189:½ Process finished with exit code 0
package Char; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Array; import java.util.Arrays; public class Test1 {//China GBK public static void main(String[] args) throws IOException { String s="China"; int len; byte[] bytes=new byte[1024]; bytes=s.getBytes("GBK"); System.out.println(Arrays.toString(bytes)); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=60636:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Char.Test1 [-42, -48, -71, -6] Process finished with exit code 0
One Chinese character storage:
UTF-8: 3 bytes
GBK: 2 bytes
Coding table
Encoding and decoding problems in strings
package Char; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Array; import java.util.Arrays; public class Test1 {//China GBK public static void main(String[] args) throws IOException { String s="China"; int len; byte[] bytes=new byte[1024]; bytes=s.getBytes(); System.out.println(new String(bytes));//Description the default decoding and encoding are UTF-8 bytes=s.getBytes("GBK"); System.out.println(Arrays.toString(bytes)); System.out.println(new String(bytes));//At this time, it is GBK encoding, but the default decoding method (UTF-8) is used, so it will be displayed й � System.out.println(new String(bytes,"GBK"));//At this time, the encoding and decoding methods are the same, so: China is displayed } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=61296:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Char.Test1 China [-42, -48, -71, -6] �й� China Process finished with exit code 0
Encoding and decoding in character stream
-
OutputStreamWriter is a bridge from character stream to byte stream: use the specified charset will The characters written into it are encoded as bytes. The character set it uses can be specified by name or explicitly, or it can accept the default character set of the platform.
Each call to the write () method causes the encoder to be called on the given character. The generated bytes accumulate in the buffer before being written to the underlying output stream. Note that the characters passed to the write () method are not buffered.
-
InputStreamReader is a bridge from byte stream to character stream: it uses the specified charset Reads bytes and decodes them into characters. The character set it uses can be specified by name or explicitly, or it can accept the default character set of the platform.
Each call to the read () method of an InputStreamReader may cause one or more bytes to be read from the underlying byte input stream. In order to achieve efficient byte to character conversion, more bytes can be extracted from the underlying stream than are required to meet the current read operation.
package OutputStreamWriter; import java.io.*; public class Test1 { public static void main(String[] args) throws IOException { // OutputStreamWriter(OutputStream out) creates an OutputStreamWriter that uses the default character encoding. // OutputStreamWriter(OutputStream out, String charsetName) creates an OutputStreamWriter using the specified charset. //Bridge between character stream and byte stream // FileOutputStream fos=new FileOutputStream("WriteTest.txt"); //fos cannot write characters directly OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("WriteTest")); //osw can osw.write("China"); // fos.close(); osw.close(); } }
package OutputStreamWriter; import java.io.*; public class Test1 { public static void main(String[] args) throws IOException { // OutputStreamWriter(OutputStream out) creates an OutputStreamWriter that uses the default character encoding. // OutputStreamWriter(OutputStream out, String charsetName) creates an OutputStreamWriter using the specified charset. //Bridge between character stream and byte stream // FileOutputStream fos=new FileOutputStream("WriteTest.txt"); //fos cannot write characters directly OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("WriteTest.txt"),"UTF-8");//Because the default is UTF-8, it is still written to China //osw can osw.write("China"); // fos.close(); osw.close(); } }
package OutputStreamWriter; import java.io.*; public class Test1 { public static void main(String[] args) throws IOException { // OutputStreamWriter(OutputStream out) creates an OutputStreamWriter that uses the default character encoding. // OutputStreamWriter(OutputStream out, String charsetName) creates an OutputStreamWriter using the specified charset. //Bridge between character stream and byte stream // FileOutputStream fos=new FileOutputStream("WriteTest.txt"); //fos cannot write characters directly OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("WriteTest.txt"),"GBK");//Because it is GBK, it is written й Garbled code (unreadable) //osw can osw.write("China"); // fos.close(); osw.close(); } }
package OutputStreamWriter; import java.io.*; public class Test1 { public static void main(String[] args) throws IOException { // OutputStreamWriter(OutputStream out) creates an OutputStreamWriter that uses the default character encoding. // OutputStreamWriter(OutputStream out, String charsetName) creates an OutputStreamWriter using the specified charset. //Bridge between character stream and byte stream // FileOutputStream fos=new FileOutputStream("WriteTest.txt"); //fos cannot write characters directly OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("WriteTest.txt"),"GBK");//Because it is GBK, it is written й Garbled code (unreadable) //osw can osw.write("China"); // fos.close(); osw.close(); // InputStreamReader(InputStream in) creates an InputStreamReader that uses the default character set. // InputStreamReader(InputStream in, String charsetName) creates an InputStreamReader using the specified charset. InputStreamReader isr=new InputStreamReader(new FileInputStream("WriteTest.txt"),"GBK"); int read; while ((read=isr.read())!=-1){ System.out.print(read); System.out.println((char)read); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=56941:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava OutputStreamWriter.Test1 20013 in 22269 country Process finished with exit code 0
Five ways of writing data in character stream
package OutputStreamWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class Test2 { public static void main(String[] args) throws IOException { // void write(char[] cbuf, int off, int len) writes a part of a character array. // void write(int c) writes a character. // void write(String str, int off, int len) writes a part of a string. OutputStreamWriter outputStreamWriter=new OutputStreamWriter(new FileOutputStream("WriteTest2.txt")); outputStreamWriter.write(97); /* In the buffer layer : new OutputStreamWriter(new FileOutputStream("WriteTest2.txt")); The data in the new OutputStreamWriter() in has not entered the new FileOutputStream("WriteTest2.txt") So there is no value in the output file flush (refresh) is required to transfer the data to FileOutputStream for implementation */ outputStreamWriter.flush();//The file displays a //Because it will refresh before calling close, the value will be displayed when calling close } }
package OutputStreamWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class Test2 { public static void main(String[] args) throws IOException { // void write(char[] cbuf, int off, int len) writes a part of a character array. // void write(int c) writes a character. // void write(String str, int off, int len) writes a part of a string. OutputStreamWriter outputStreamWriter=new OutputStreamWriter(new FileOutputStream("WriteTest2.txt")); //outputStreamWriter.write(97); /* In the buffer layer : new OutputStreamWriter(new FileOutputStream("WriteTest2.txt")); The data in the new OutputStreamWriter() in has not entered the new FileOutputStream("WriteTest2.txt") So there is no value in the output file flush (refresh) is required to transfer the data to FileOutputStream for implementation */ // outputStreamWriter.flush();// The file displays a //Because it will refresh before calling close, the value will be displayed when calling close char[] s={'a','b','c','d','e'}; outputStreamWriter.write(s);//abcde outputStreamWriter.write(s,1,3);//bcd outputStreamWriter.write("abcde",0,"abcde".length());//abcde outputStreamWriter.close(); } }
Two ways of reading data from character stream
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-7ndl9vxv-1618645073327)( https://i.loli.net/2021/04/17/46rlMDLmINejHf3.png )]
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; public class InputStreamRead { public static void main(String[] args) throws IOException { InputStreamReader inputStreamReader=new InputStreamReader(new FileInputStream("inputObject2.txt")); int read; while ((read=inputStreamReader.read())!=-1){ System.out.print((char) read); } inputStreamReader.close(); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=59484:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava InputStreamRead package InputStream; import java.io.*; /* method1 It takes 999999 (too many) ms in total method2 Total time: 5264ms(array) method3 It takes 15821ms in total method4 It takes 1050ms in total (array) */ public class BufferedCompareCommon { public static void main(String[] args) throws IOException { //Record start time long startTime=System.currentTimeMillis(); method2(); //Record end time long endTime=System.currentTimeMillis(); System.out.println("Total time"+(endTime-startTime)+"ms"); } public static void method3() throws IOException { BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream("video.mp4")); BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream("pasteVideo.mp4")); int read; while ((read=bufferedInputStream.read())!=-1){ bufferedOutputStream.write(read); } bufferedInputStream.close(); bufferedOutputStream.close(); } public static void method4() throws IOException { BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream("video.mp4")); BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream("pasteVideo.mp4")); int read; byte[] bytes=new byte[1024]; while ((read=bufferedInputStream.read(bytes))!=-1){ bufferedOutputStream.write(bytes,0,read); } bufferedInputStream.close(); bufferedOutputStream.close(); } public static void method2() throws IOException { FileInputStream bufferedInputStream=new FileInputStream("video.mp4"); FileOutputStream bufferedOutputStream=new FileOutputStream("pasteVideo.mp4"); int read; byte[] bytes=new byte[1024]; while ((read=bufferedInputStream.read(bytes))!=-1){ bufferedOutputStream.write(bytes,0,read); } bufferedInputStream.close(); bufferedOutputStream.close(); } public static void method1() throws IOException { FileInputStream bufferedInputStream=new FileInputStream("video.mp4"); FileOutputStream bufferedOutputStream=new FileOutputStream("pasteVideo.mp4"); int read; while ((read=bufferedInputStream.read())!=-1){ bufferedOutputStream.write(read); } bufferedInputStream.close(); bufferedOutputStream.close(); } } Process finished with exit code 0
Case copy Java file
package OutputStreamWriter; import java.io.*; public class Text3 { public static void main(String[] args) throws IOException { InputStreamReader reader=new InputStreamReader(new FileInputStream("InputStreamRead.java")); OutputStreamWriter writer=new OutputStreamWriter(new FileOutputStream("CopeJavaFile.java")); int read; while ((read=reader.read())!=-1){ writer.write(read); } writer.close(); reader.close(); } }
package OutputStreamWriter; import java.io.*; public class Text3 { public static void main(String[] args) throws IOException { InputStreamReader reader=new InputStreamReader(new FileInputStream("InputStreamRead.java")); OutputStreamWriter writer=new OutputStreamWriter(new FileOutputStream("CopeJavaFile.java")); int read; char[] chars=new char[1024]; while ((read=reader.read(chars))!=-1){ writer.write(chars,0,read); } writer.close(); reader.close(); } }
Copy Java files – improved
package OutputStreamWriter; import java.io.*; public class Text3 { public static void main(String[] args) throws IOException { FileReader reader=new FileReader("InputStreamRead.java"); FileWriter writer=new FileWriter("CopeJavaFile.java"); int read; char[] chars=new char[1024]; while ((read=reader.read(chars))!=-1){ writer.write(chars,0,read); } writer.close(); reader.close(); } }
Character buffer stream
package Char; import java.io.*; public class Buffered { public static void main(String[] args) throws IOException { FileWriter fileWriter=new FileWriter("BufferedFileWriter.txt"); BufferedWriter bufferedWriter=new BufferedWriter(fileWriter); bufferedWriter.write("Hello\r\n"); bufferedWriter.write("World\r\n"); //The buffer stream needs to be refreshed before it is displayed bufferedWriter.close(); //read BufferedReader bufferedReader=new BufferedReader(new FileReader("BufferedFileWriter.txt")); int read; char[] chars=new char[1024]; while ((read=bufferedReader.read(chars))!=-1) {//Read the character array not with (char) read but with new String(chars,0,read) System.out.println( new String(chars,0,read)); } bufferedReader.close(); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=60335:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Char.Buffered Hello World Process finished with exit code 0
Case copy Java file character buffer stream version
Unique function of character buffer stream
package Char; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class SpecialFoundation { public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter("SpecialTest.txt")); //Because \ R \ nline break is only applicable to Window system, BufferedWriter provides newLine method to adapt to all systems for (int i=0;i<10;i++){ bufferedWriter.write("Hello"+i); bufferedWriter.newLine(); } bufferedWriter.close(); } }
package Char; import java.io.*; public class SpecialFoundation { public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter("SpecialTest.txt")); //Because \ R \ nline break is only applicable to Window system, BufferedWriter provides newLine method to adapt to all systems for (int i=0;i<10;i++){ bufferedWriter.write("Hello"+i); bufferedWriter.newLine(); } bufferedWriter.close(); //BufferedReader also provides a method to read one line at a time. The content read by readLine does not contain termination symbols (line breaks, etc.). If the end of the stream arrives, null will be displayed BufferedReader bufferedReader=new BufferedReader(new FileReader("SpecialTest.txt")); //for (int i=0;i<10;i++){ // System.out.print(bufferedReader.readLine()); // } /* Hello0Hello1Hello2Hello3Hello4Hello5Hello6Hello7Hello8Hello9 */ //Forced line feed required // for (int i=0;i<10;i++){ // System.out.println(bufferedReader.readLine()); // } /* "C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=60625:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Char.SpecialFoundation Hello0 Hello1 Hello2 Hello3 Hello4 Hello5 Hello6 Hello7 Hello8 Hello9 Process finished with exit code 0 */ //So we have String s; while ((s=bufferedReader.readLine())!=null){ System.out.println(s); } } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=60648:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Char.SpecialFoundation Hello0 Hello1 Hello2 Hello3 Hello4 Hello5 Hello6 Hello7 Hello8 Hello9 Process finished with exit code 0
Case - the unique function of character buffer stream to copy files
package Char; import java.io.*; public class CopeBuffered { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new FileReader("InputObjectBuffer.txt")); BufferedWriter bw=new BufferedWriter(new FileWriter("OutputObjectBuffer.txt")); String line; while ((line=br.readLine())!=null){ bw.write(line); //Wrap every line written bw.newLine(); } br.close(); bw.close(); } }
IO Flow Summary
Case - assemble to file
package Char; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class Array { public static void main(String[] args) throws IOException { ArrayList<String> arrayList=new ArrayList<String>(); arrayList.add("Hello"); arrayList.add("Java"); arrayList.add("World"); BufferedWriter bw=new BufferedWriter(new FileWriter("array.txt")); for (String s:arrayList){ bw.write(s); bw.newLine(); bw.flush(); } bw.close(); } }
Cases - files to collections
package Char; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class FiletoArray { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new FileReader("array.txt")); ArrayList<String> arrayList=new ArrayList<String>(); String line; while ((line=br.readLine())!=null){ arrayList.add(line); } for (String s:arrayList){ System.out.println(s); } br.close(); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=54899:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Char.FiletoArray Hello Java World Process finished with exit code 0
Case - roll call
package Test1; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Random; public class CallName { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new FileReader("CallNameFile.txt")); ArrayList<String> al=new ArrayList<String>(); String line; while ((line=br.readLine())!=null){ al.add(line); } Random a=new Random(); int i=a.nextInt(al.size()); System.out.println("lucky:"+al.get(i)); br.close();a } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=55349:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Test1.CallName lucky:Li Si Process finished with exit code 0
Case - assemble to file (student)
package Java1; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class ArrayToFileAboutStudent { public static void main(String[] args) throws IOException { ArrayList<StudentTest1> arrayList=new ArrayList<StudentTest1>(); StudentTest1 s1=new StudentTest1("xiaoli",19,"Beijing","001"); StudentTest1 s2=new StudentTest1("wangwu",32,"Wuhan","002"); StudentTest1 s3=new StudentTest1("zhangsan",20,"HaiNan","003"); BufferedWriter writer=new BufferedWriter(new FileWriter("ArrayToFileAboutStudent.txt")); arrayList.add(s1); arrayList.add(s2); arrayList.add(s3); for (StudentTest1 s:arrayList){ StringBuilder sb=new StringBuilder(); sb.append(s.getId()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress()); System.out.println(sb); //Write because StringBuilder sb (sb. Tostring()) (requires String parameter) writer.write(sb.toString()); writer.newLine(); writer.flush(); } writer.close(); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=53235:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.ArrayToFileAboutStudent 001,xiaoli,19,Beijing 002,wangwu,32,Wuhan 003,zhangsan,20,HaiNan Process finished with exit code 0
Case - file to set (student)
package Java1; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class FiletoarrayStudent { public static void main(String[] args) throws IOException { ArrayList<StudentTest1> arrayList=new ArrayList<StudentTest1>(); BufferedReader bufferedReader=new BufferedReader(new FileReader("ArrayToFileAboutStudent.txt")); String line; while ((line=bufferedReader.readLine())!=null){ String[] array=line.split(","); //An array of strings with, as the dividing line //{001,xiaoli,19,Beijing} StudentTest1 s=new StudentTest1(); s.setName(array[1]); s.setAge(Integer.parseInt(array[2])); s.setAddress(array[3]); s.setId(array[0]); arrayList.add(s); } for (StudentTest1 s:arrayList){ StringBuilder sb=new StringBuilder(); sb.append(s.getId()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress()); System.out.println(sb); } bufferedReader.close();} }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=54169:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.FiletoarrayStudent 001,xiaoli,19,Beijing 002,wangwu,32,Wuhan 003,zhangsan,20,HaiNan Process finished with exit code 0
Case - assemble to file (sorted version)
package Java1; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Comparator; import java.util.Scanner; import java.util.TreeSet; public class ArrayToFileCompare { public static void main(String[] args) throws IOException { TreeSet<ScoreTest1> treeSet=new TreeSet<ScoreTest1>(new Comparator<ScoreTest1>() { @Override public int compare(ScoreTest1 o1, ScoreTest1 o2) { double num=o2.getSum()-o1.getSum(); double num2=num==0?o2.getMath()-o1.getMath():num; double nu3=num2==0?o2.getName().compareTo(o1.getName()):num2; if(nu3>0){ return 1; }else return -1; } }); //ScoreTest1 scoreTest1=new ScoreTest1(); It cannot be placed outside the loop because it puts the value into the collection. If the value is changed, all previous values will be changed to the latest value Scanner sc=new Scanner(System.in); /* "C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=57722:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.ArrayToFileCompare please input1 name of student 000 please input1 student Chinese score 55 please input1 student Math score 44 please input2 name of student 001 please input2 student Chinese score 45 please input2 student Math score 56 001chinese :45.0math :56.0sum :101.0 001chinese :45.0math :56.0sum :101.0 */ for (int i=0;i<5;i++) { ScoreTest1 scoreTest1=new ScoreTest1(); System.out.println("please input" + (i + 1) + " name of student"); String s1=sc.next(); scoreTest1.setName(s1); System.out.println("please input" + (i + 1) + " student Chinese score"); double s2=sc.nextDouble(); scoreTest1.setChinese(s2); System.out.println("please input" + (i + 1) + " student Math score"); double s3=sc.nextDouble(); scoreTest1.setMath(s3); treeSet.add(scoreTest1); } BufferedWriter bf=new BufferedWriter(new FileWriter("Score.txt")); for (ScoreTest1 s:treeSet){ StringBuilder stringBuilder=new StringBuilder(); stringBuilder.append(s.getName()).append("chinese :").append(s.getChinese()).append("math :").append(s.getMath()).append("sum :").append(s.getSum()); System.out.println(stringBuilder.toString()); bf.write(stringBuilder.toString()); bf.newLine(); bf.flush(); } bf.close(); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=58018:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.ArrayToFileCompare please input1 name of student list please input1 student Chinese score 45 please input1 student Math score 78 please input2 name of student leaf please input2 student Chinese score 78 please input2 student Math score 69 please input3 name of student explore please input3 student Chinese score 99 please input3 student Math score 66 please input4 name of student Oh, oh please input4 student Chinese score 87 please input4 student Math score 66 please input5 name of student spacing please input5 student Chinese score 77 please input5 student Math score 98 spacing chinese :77.0math :98.0sum :175.0 explore chinese :99.0math :66.0sum :165.0 Oh, oh chinese :87.0math :66.0sum :153.0 leaf chinese :78.0math :69.0sum :147.0 list chinese :45.0math :78.0sum :123.0 Process finished with exit code 0
exit code 0
###### Case - roll call device [External chain picture transfer...(img-XA4mU6OO-1618645073353)] ```java package Test1; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Random; public class CallName { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new FileReader("CallNameFile.txt")); ArrayList<String> al=new ArrayList<String>(); String line; while ((line=br.readLine())!=null){ al.add(line); } Random a=new Random(); int i=a.nextInt(al.size()); System.out.println("lucky:"+al.get(i)); br.close();a } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=55349:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Test1.CallName lucky:Li Si Process finished with exit code 0
Case - assemble to file (student)
[external chain picture transferring... (IMG ixlxlmau-1618645073354)]
package Java1; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class ArrayToFileAboutStudent { public static void main(String[] args) throws IOException { ArrayList<StudentTest1> arrayList=new ArrayList<StudentTest1>(); StudentTest1 s1=new StudentTest1("xiaoli",19,"Beijing","001"); StudentTest1 s2=new StudentTest1("wangwu",32,"Wuhan","002"); StudentTest1 s3=new StudentTest1("zhangsan",20,"HaiNan","003"); BufferedWriter writer=new BufferedWriter(new FileWriter("ArrayToFileAboutStudent.txt")); arrayList.add(s1); arrayList.add(s2); arrayList.add(s3); for (StudentTest1 s:arrayList){ StringBuilder sb=new StringBuilder(); sb.append(s.getId()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress()); System.out.println(sb); //Write because StringBuilder sb (sb. Tostring()) (requires String parameter) writer.write(sb.toString()); writer.newLine(); writer.flush(); } writer.close(); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=53235:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.ArrayToFileAboutStudent 001,xiaoli,19,Beijing 002,wangwu,32,Wuhan 003,zhangsan,20,HaiNan Process finished with exit code 0
[external chain picture transferring... (img-tMUDrZjl-1618645073356)]
Case - file to set (student)
[external chain picture transferring... (img-NA9N6Iap-1618645073357)]
package Java1; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class FiletoarrayStudent { public static void main(String[] args) throws IOException { ArrayList<StudentTest1> arrayList=new ArrayList<StudentTest1>(); BufferedReader bufferedReader=new BufferedReader(new FileReader("ArrayToFileAboutStudent.txt")); String line; while ((line=bufferedReader.readLine())!=null){ String[] array=line.split(","); //An array of strings with, as the dividing line //{001,xiaoli,19,Beijing} StudentTest1 s=new StudentTest1(); s.setName(array[1]); s.setAge(Integer.parseInt(array[2])); s.setAddress(array[3]); s.setId(array[0]); arrayList.add(s); } for (StudentTest1 s:arrayList){ StringBuilder sb=new StringBuilder(); sb.append(s.getId()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress()); System.out.println(sb); } bufferedReader.close();} }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=54169:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.FiletoarrayStudent 001,xiaoli,19,Beijing 002,wangwu,32,Wuhan 003,zhangsan,20,HaiNan Process finished with exit code 0
Case - assemble to file (sorted version)
[external chain picture transferring... (img-RgLd6xb4-1618645073359)]
package Java1; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Comparator; import java.util.Scanner; import java.util.TreeSet; public class ArrayToFileCompare { public static void main(String[] args) throws IOException { TreeSet<ScoreTest1> treeSet=new TreeSet<ScoreTest1>(new Comparator<ScoreTest1>() { @Override public int compare(ScoreTest1 o1, ScoreTest1 o2) { double num=o2.getSum()-o1.getSum(); double num2=num==0?o2.getMath()-o1.getMath():num; double nu3=num2==0?o2.getName().compareTo(o1.getName()):num2; if(nu3>0){ return 1; }else return -1; } }); //ScoreTest1 scoreTest1=new ScoreTest1(); It cannot be placed outside the loop because it puts the value into the collection. If the value is changed, all previous values will be changed to the latest value Scanner sc=new Scanner(System.in); /* "C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=57722:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.ArrayToFileCompare please input1 name of student 000 please input1 student Chinese score 55 please input1 student Math score 44 please input2 name of student 001 please input2 student Chinese score 45 please input2 student Math score 56 001chinese :45.0math :56.0sum :101.0 001chinese :45.0math :56.0sum :101.0 */ for (int i=0;i<5;i++) { ScoreTest1 scoreTest1=new ScoreTest1(); System.out.println("please input" + (i + 1) + " name of student"); String s1=sc.next(); scoreTest1.setName(s1); System.out.println("please input" + (i + 1) + " student Chinese score"); double s2=sc.nextDouble(); scoreTest1.setChinese(s2); System.out.println("please input" + (i + 1) + " student Math score"); double s3=sc.nextDouble(); scoreTest1.setMath(s3); treeSet.add(scoreTest1); } BufferedWriter bf=new BufferedWriter(new FileWriter("Score.txt")); for (ScoreTest1 s:treeSet){ StringBuilder stringBuilder=new StringBuilder(); stringBuilder.append(s.getName()).append("chinese :").append(s.getChinese()).append("math :").append(s.getMath()).append("sum :").append(s.getSum()); System.out.println(stringBuilder.toString()); bf.write(stringBuilder.toString()); bf.newLine(); bf.flush(); } bf.close(); } }
"C:\Program Files\AdoptOpenJDK\jdk-11.0.9.101-hotspot\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=58018:D:\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\heimaJava\out\production\heimaJava Java1.ArrayToFileCompare please input1 name of student list please input1 student Chinese score 45 please input1 student Math score 78 please input2 name of student leaf please input2 student Chinese score 78 please input2 student Math score 69 please input3 name of student explore please input3 student Chinese score 99 please input3 student Math score 66 please input4 name of student Oh, oh please input4 student Chinese score 87 please input4 student Math score 66 please input5 name of student spacing please input5 student Chinese score 77 please input5 student Math score 98 spacing chinese :77.0math :98.0sum :175.0 explore chinese :99.0math :66.0sum :165.0 Oh, oh chinese :87.0math :66.0sum :153.0 leaf chinese :78.0math :69.0sum :147.0 list chinese :45.0math :78.0sum :123.0 Process finished with exit code 0