This article is constantly updating the Java foundation that should be mastered when using the Java language on the computer
It is not to explain the basic syntax of java in detail
input
Scaner scaner = new Scaner (System.in); //Enter numbers int number = scaner.nextInt(); //Input string String string = scaner.next();// Do not accept the following symbols, that is, input the following symbols, and the current input will not be ended String string = scaner.nextLine();// Receive carriage return, line feed, TAB
next() And
nextLine() Input difference
next() You must make valid input (not including the character of the ending symbol) before you can end the input (otherwise, you are always waiting for input), and then use the ending symbol to end the current input (carriage return, line feed, TAB, or space) nextLine() : There is no constraint above. You can receive any character and only enter one ending symbol, so you can enter a string containing spaces.
next() After receiving the carriage return and finishing the input, \n It will not disappear (either filtered by the next next() or filtered by the next NextLine() receive ) nextLine() Receive the carriage return, and remove it after the input is completed \n , so next nextLine() Can receive input normally, but not enter 。
-
Valid input, next() You must receive a valid input to end the input. nextLine() Can receive directly enter End character (actually received as null "" , because the carriage return will be automatically removed). -
Different types of ending symbols -
Pair ending symbol enter The processing of is different
Format Input
Multiple groups of data input, uncertain group number, end with EOF.
while(sc.haveNext()){ // }
output
//First DecimalFormat df = new DecimalFormat("#0.00"); float data; data = sc.nextFloat(); System.out.println(df.format(data)); //The second is to imitate the output mode of C language, but without line breaking System. out. printf ("%. 2f n", data);//Keep two decimal places System. out. printf ("% 5d", n);//The domain width is 5 Format characters: %- 0 m.n [type symbol] ① %: indicates the starting symbol of format description, which is indispensable. ② -: Yes - means left aligned output, if omitted, right aligned output. ③ 0: if there is 0, it means that the specified empty space is filled with 0. If omitted, it means that the specified empty space is not filled. ④ M.n: m refers to the field width, that is, the number of characters occupied by the corresponding output item on the output device. (If the number of output digits is less than m digits, the left end is filled with spaces by default. The number of characters refers to the position of the whole real number, including the decimal point.) n refers to the precision. The number of decimal places used to describe the output real number. When n is specified, the implied precision is n=6 bits. ⑤ [Type symbol] d represents integer f represents floating point number //Third System.out.println(String.format("%.2f", data));
Basic data type
Int 4 bytes (32bit) - 2 ^ 31~2 ^ 31 - 1
Short 2 bytes (16bit) - 2 ^ 15~2 ^ 15 - 1
Long 8 bytes (64bit) - 2 ^ 63~2 ^ 63 - 1
Float 4 bytes (32bit) 2 ^ - 149~2 ^ 128 - 1
Double 8 bytes (64bit) 2 ^ - 1074~2 ^ 1024 - 1
Char 1 byte
Common methods
//Compare Size //Compares two strings in dictionary order. a.compareTo(b);// If a>b returns a number greater than 0 //Type conversion int Interger.parseInt(String s); Interger Interger.valueOf(String/int s); //Judge whether it is a number Character.isDigit(String s);
Binary conversion
//Other decimal to decimal Integer. valueOf ("[numeric string]", [decimal number]). toString() //Decimal to binary Integer.toBinaryString(int i) //Decimal to octal Integer.toOctalString(int i) //Decimal to hexadecimal Integer.toHexString(int i)
ASCII code of characters
character string
Fetch substring
//The substring method is used to extract the characters between the string stringObject and two specified subscripts [start, stop]. The position of stop will not be taken, and stop will not be written. The default is to the end of the string testString.substring(start,stop); //No length, all the way to the end stringObject.substr(start [, length ]);
Substring lookup
Returns the position of the first character of the matched substring in the original string
string.indexof(String s);// Returns the index of the first occurrence of the specified substring in this string. String. indexof (String s, int startIndex);//Starting from the specified index, returns the index of the first occurrence of the specified substring in this string. LastIndexOf (String str)//Returns the index of the specified substring that appears on the rightmost side of the string. LastIndexOf (String str, int startIndex)//Search backwards from the specified index to return the index of the specified substring that last appeared in the string. ?
Determine whether such substring exists
string.contains(String s);
characters finding
string.charAt(index)
Character array conversion
//Convert char array to String char data[] = {'s', 'g', 'k'}; String str = new String(data); str = String.valueOf(data);
String construction
//String construction StringBuilder s = new StringBuilder(); StringBuilder s = new StringBuilder(String s);// Take string as parameter directly s.append(String s); s. Reverse()//Invert the sequence s. Delete (int start, int end)//Removes characters in the specified range s. Insert (int offset, i)//Insert characters or strings at the specified position, which can be said to include the append function s. Replace (int start, int end, String str)//Replace the substring of the specified SN range with a new string
replace
-
The String replace method does not modify its own string content, but returns a new string -
StringBuilder is Replace a new string by range , String is matched by character or regular, Replace all matches 。
String. replace (char a, char b);//Replace all a characters with b characters String. replaceAll (regex, String replace);//Replace according to the regular expression
aggregate
Use of java iterator
List<String> list = new ArrayList<>(); list.add("*"); list.add("*"); list.add("*"); list.add("*"); for (int i = 0; i < list.size(); i++){ if(list.get(i).equals("*")){ list.remove(i); } System.out.println(i + "|" + list.size());// commented code } System.out.println(list);
0|3 1|2 [*, *]
for (Iterator iterator = list.iterator(); iterator.hasNext();) { String string = (String) iterator.next(); if(string.equals("*")){ iterator.remove(); } }
Iterater
hasNext();// If the iterator points to an element after the position, it returns true; otherwise, it returns false next();// Return the element after the Iterator points to the position in the collection remove();// Delete the element after the Iterator points to the position in the collection
ListIterator
//Get the index of the current element (obtained indirectly through the index of the previous or next element): nextIndex()-1; previousIndex()+1; //Output in reverse order, obtain ListIterator, and pass the list size as a parameter: for (ListIterator iterator = list.listIterator(list.size()); iterator.hasPrevious();) { String string = (String) iterator.previous(); System.out.print(string); } //Add Element add(E e); //Modify Element set(E e);
List
//Create linked list List<Integer> list = new ArrayList(); //Add Data list.add(val); //Delete list.remove(int index); list.remove(Object object);// The equal method of the class needs to be overridden iterator.remove(); //Insert data at specified position List. add (pos, val);//It will not be overwritten. The original value of this position and the subsequent values will automatically move one bit backward List. set (pos, val);//Overwrite the value of pos position (modify the element value) //Query the value of the specified location list.get(pos); //Judge whether an element value exists list.contains(val);// Returns true false list.indexof(val);// Return the position of the first match or - 1 //Array to list ArrayList<String> list = new ArrayList<String>(Arrays.asList(strArray)) ; //Merge Arrays list.addAll(List list2); //List to array String[] sss = listStrings.toArray(new String[listStrings.size()]); //List to String Loop through the list and use the append method of StringBuilder //Sort Collections.sort(list);// Default Ascending Collections.sort(listCollections.reverseOrder();// Sort Descending //Customized sorting interface. Returning 1 indicates that o1 and o2 need to switch left and right, and - 1 indicates that no move is required. 0 means that the two values are equal. //Remove duplicate elements List to set and then to list list = new ArrayList<>(new LinkedHashSet<>(list));// LinkedHashSet is used here because it ensures that the addition order of elements is consistent with the previous list
yes Collection member is not a List of basic data type De duplication?
set
PriorityQueue
//Implement the big top heap and pass the Comparator parameter during construction //The initialization heap size is arbitrary. Even if it is 1, new elements can be added continuously Queue<ListNode>priorityQueue=new PriorityQueue<ListNode>([initialization heap size], new Comparator<ListNode>(){ @Override public int compare(ListNode o1, ListNode o2) { return o1.val-o2.val; } });
//Definition PriorityQueue<Integer> list = new PriorityQueue<Integer>(); //Add elements list.add(int) list.offer(int); //Get the first element of the team, but do not delete it list.peek(); //Get the first element of the team and delete it list.poll();
Stack
Stack<Interger> stack = new Stack(); stack.isEmpty();// Determine whether the stack is empty Stack. ClearStack: empty the stack stack.size();// That is, the stack length stack.peek();// Return top stack element stack.push();// Stack stack.pop();// Return the top stack element and delete it
Map
//Create map Map<Integer,Integer> map = new HashMap<>(); //Insert/Modify Element map.put(key,val); map.putAll(Map t) //Query by Key map.get(key); //Delete Element map.remove(key); //Sort by key (Sort in descending order) The core is to convert map to list, and then sort the list //Convert map to list Set<Map.Entry<Integer, Integer>> entrys = map.entrySet();// Use this to obtain the set of map key value pairs List<Map.Entry<Integer, Integer>> = new ArrayList<>(entrys);// The element type of list is set<Map. entry<Integer, Integer>>type
Reference article: https://baike.xsoftlab.net/view/250.html
array
//Define an empty array int [] empty = new int[5]; //Define an array with initial values int [] have = new int[]{1,2,3};
Common methods of Math class
//Calculate a to the power of b, a ^ b Math.pow(double a, double b) System.out.println(Math.pow(2, 3)); // eight //Calculate the power a of the natural constant, e ^ a Math.exp(double a) System.out.println(Math.exp(1)); // two point seven one eight two eight one eight two eight four five nine zero four five //Calculate the square root, √ a Math.sqrt(double a) System.out.println(Math.sqrt(16)); // four //Calculate the cube root, a ‾ √ 3a3 Math.cbrt(double a) System.out.println(Math.cbrt(8)); // two //Calculate the base e logarithm (natural logarithm), logexlog ex or lnxln x Math.log(double x) System.out.println(Math.log(Math.E)); // one //Calculate the base 10 logarithm, log10xlog 10x or lgxlg x Math.log10(double x) System.out.println(Math.log10(100)); // two //Calculate absolute value, parameter type: int long、float、double Math.abs(int x) System.out.println(Math.abs(-1)); // one //The Random. nextDouble() method is called internally to generate a pseudo evenly distributed double value between 0.0 and 1.0 Math.random(); System.out.println((int)(Math.random() * 10 + 1)); // Generate pseudo-random numbers in the range [1, 11] //Get the maximum value of two parameters. Parameter type: int long、float、double Math.max(int x, int y) System.out.println(Math.max(1, 2)); // two //Get the minimum value of two parameters. Parameter type: int long、float、double Math.min(int x, int y) System.out.println(Math.min(1, 2)); // one
regular expression
Patten Receive regular expression as parameter Matcher stay Matcher On the basis, receive strings as parameters
Split String
//Method 1: use the method provided by the String class TestString. split ([regular expression], [limit]); //Mode 2 Patten p = Pattern.compile("\\d+"); p.split([string],[limit]) /*Limit is optional. The limit parameter controls the number of times the mode is applied, thus affecting the length of the result array. 1. If n is greater than zero, the mode can be applied at most n-1 times, the length of the array is not greater than n, and the last entry of the array will contain all inputs except the last matching delimiter. 2. If n is not positive, the number of times the mode is applied is unlimited, and the array can be of any length. 3. If n is zero, the number of times to apply the mode is unlimited, the array can be of any length, and the trailing empty string will be discarded. */
Determine whether a segment exists in the string and find the position of the matching substring
//Mode 1: Patten static method or instance method [exact match] Patten.matcher (String regex, CharSequence input);//Returns true or false Patten.matches("\\d+","2223");// Return true Patten.matches("\\d+","2223aa");// Return false Patten.matches("\\d+","22bb23");// Return false //Method 2: Matcher class method m.matches();// [Exact match], the same effect as above m.lookingAt();// Partial Matching. 223aa returns true //Note: through m.matchs()/m.lookingAt()/m.find(), the pointer will move to the next matching string position, which will affect the results of subsequent m.find() operations. m.reset();// Reset the position of the matching pointer Matcher m = p.mather(testString); m.find();// Partial Matching returns true or false, and the pointer will move to the next matching position while(m.find()) { System. out. println ("position 1"+m.start()); System. out. println ("position 2"+m.end()); System.out.println(m.group());// m. Group() returns the current matching string System.out.println(m.groupCount());// Returns the number of currently matched groups System.out.println(m.group(0));// Returns the first set of strings of the current string }
ScriptEngineManager
ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("javascript"); //Get the execution engine according to the "Script Language Name". Java only supports javascript by default //The getEngineByName method creates a new Engine object each time String script = "3+4*5"; int result = engine.eval(script); System.out.println(total);
Data structure and algorithm
data structure
tree
Sequential storage structure of tree( Father representation )
public class Tree { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); //Information of n nodes and n-1 edges int [] edges = new int [n+1];// Node numbering starts from 1 edges[1] = -1; for (int i = 0; i < n-1; i++) { int parent = scanner.nextInt(); int child = scanner.nextInt(); edges[child] = parent; } for (int i = 0; i < edges.length; i++) { System.out.print(edges[i] + " | "); } System.out.println(); tree_print(edges); } public static void tree_print(int[] edges) { for (int i = 1; i < edges.length; i++) { System.out.println(i); for (int j = 1; j < edges.length; j++) { if (edges[j] == i) { System.out.print(j + "|"); } } System.out.println(); } } }
Chain storage structure of tree
Binary tree
Binary linked list structure
class TreeNode{ int value; TreeNode left; TreeNode right; public TreeNode(int value) { this.value = value; this.left = null; this.right = null; } public TreeNode() { } }
chart
adjacency matrix
class MGraph { Int vertexNum;//Number of vertices Int edgesNum;//The number of sides int[][] edges;// Two dimensional matrix, indicating whether there is a edge between any two points }
Adjacency list
heap
algorithm
Dijestra shortest path
-
Set T, the initial state is the set of all vertices except vertex O. -
Set S, initial state only vertex O -
Dist [], the distance from the source point to all other vertices. In the initial state, if the vertex O is directly connected to other vertices, the value is the weight of the edge. If not, the value is ∞ (a large number is defined in programming) -
Path [], the number of the previous node in the shortest path from the source point to the target node. In the initial state, if vertex O is directly connected with other vertices, the value is the number of source point O; if not, the value is - 1
-
Each time, suck a node from T set to S set (star attraction method). This node is characterized by Source point O The path length to this node is the smallest And use this node as the Middleman , Modify Source point to other nodes of T set (Here you only need to find other nodes in the T set, not all nodes except the source point!!). If dist [middle point]+distance △<dist [other nodes]: -
Modify dist [other nodes]=dist [middle point]+distance △ -
Modify path [other nodes]=middle point
-
-
Remove the midpoint from the T set
Java positive infinity: represented by POSITIVE_INFINITY of Double or Float.
Negative infinity: it is represented by the NEGATIVE_INFINITY of Double or Float.
Non number: represented by NaN of Double or Float.
class MGraph { int vertexNum; int edgesNum; int[][] edges; int[][] dist; List<Integer> T = new ArrayList<Integer>();// T set public void initEmptyDist() { dist = new int[vertexNum + 1][vertexNum + 1]; edges = new int[vertexNum + 1][vertexNum + 1]; for (int i = 1; i <= vertexNum; i++) { for (int j = 1; j <= vertexNum; j++) { dist[i][j] = -1; edges[i][j] = -1; } } } public void Dijkstra(int origin) { //1. Initialize T set for (int i = 1; i <= vertexNum; i++) { if (i != origin) { T.add(i); } } while (T.size() != 0) { Int selectVertex=- 1;//The vertex number of the shortest path from the source point to the vertex in the T set Int selectVertexInT=0;//The vertex with the shortest path from the source point to the vertex in the T set has the serial number in the T set, because it will be deleted from the T set later Int min=- 1;//The shortest path from the source point to the vertex in the T set //2. Select intermediate node for (int i = 0; i < T.size(); i++) { if (dist[origin][T.get(i)] != - 1 && (dist[origin][T.get(i)] < min || min == -1)) { min = dist[origin][T.get(i)]; selectVertex = T.get(i); selectVertexInT = i; } } // 3. Modify other nodes in the T set with intermediate points for (int i = 0; i < T.size(); i++) { int currentTargetVertex = T.get(i); int query = query(selectVertex, currentTargetVertex); if (query != - 1) { int modified = min + query(selectVertex, currentTargetVertex); if (dist[origin][currentTargetVertex] == -1 || dist[origin][currentTargetVertex] > modified) { dist[origin][currentTargetVertex] = modified; } } } //4. Remove intermediate nodes from the T set T.remove(selectVertexInT); } } //Query the distance between two vertices in the graph public int query(int start, int end) { int result = -1; if (edges[start][end]!= - 1) { result = edges[start][end]; } return result; } }
Floyd shortest path
-
Dist [] [], the value of the shortest path of any two nodes, the initial state is the value of the two node edges in the figure, and the initial state is the critical matrix -
Path [] [], the previous node of the shortest path of any two nodes. All values in the initial state are - 1, indicating that there is no intermediate point (this initial value is different from Dijstra)
-
Take each vertex as an intermediate vertex, and then compare disti with disti+distk to determine whether to modify the shortest path.
MGraph mGraph = new MGraph(); //Omit the assignment code to the figure //1. Initialize dist [] [] array mGraph.initA_array(); //2. Triple loop, taking each vertex as the middle point for (int i = 1; i<= mGraph.getVertexNum(); i++){// circle each vertex as an intermediate point for (int k=1; k <= mGraph.getVertexNum(); k++){ for (int j = 1; j <= mGraph.getVertexNum(); j++){ if (mGraph. A[i][j] > mGraph. A[i][k] + mGraph. A[k][j]){ mGraph.A[i][j] = mGraph. A[i][k] + mGraph. A[k][j]; } } } } class MGraph{ int vertexNum; int edgeNum; int edges[][] = new int[51][51]; int A[][] = new int[51][51];// It's dist [] [] //When instantiating a graph, you need to first assign the edge of any two nodes to - 1 public MGraph() { for (int i = 0; i<51;i++){ for (int j = 0; j< 51;j++){ edges[i][j] = -1;// init edges array } } } //Initialize dist array, equivalent to edge [] [] adjacency matrix array public void initA_array(){ for (int i = 1; i<=this.getVertexNum(); i++){ for (int j = 1; j<=this.getVertexNum(); j++){ If (edges [i] [j]==- 1) {//Two nodes have no edges A[i][j] = this.vertexNum;// The number of nodes is regarded as unreachable, because the distance between two points cannot exceed the number of nodes }else { A[i][j] = edges[i][j]; } } } } }
Full arrangement
permutation(list, 0, list.size() - 1); public void permutation(List<Integer> list, int from, int to) { if (to < from) return; if (from == to) { //Now the list is a new arrangement } else { for (int i = from; i <= to; i++) { swap(list, i, from); permutation(list, from + 1, to); swap(list, from, i); } } } public void swap(List<Integer> s, int i, int j) { int tmp = s.get(i); s.set(i, s.get(j)); s.set(j, tmp); }
Eclipse settings
Code prompt
Common shortcut keys for eclipse
// command = ctrl (windows) Alt+/Prompt Command+/Current line comment Command+d Delete the current line command + 1 Quick fix syso : System.out.println();
OJ FAQ
The sample is correct, and AC fails
-
Special examples were not taken into account, such as the first question of score addition in 2014 online research -
Copy past code without package name package bupt; He does not prompt for compilation errors, but the answer is an error -
First, determine whether you understand the question correctly -
Then test critical conditions, special conditions -
Runtime error: memory out of limit, not some array or collection data out of limit, but memory out of limit
Some precautions
-
Pay attention to the variable initialization position. If it is written inside the loop and outside the loop, it is far from perfect -
Note should not be deleted before AC is successful, otherwise, note should be added later
==
Difference between and equals
-
about == If it is applied to a variable of basic data type, directly compare whether its stored "value" is equal; If it acts on a variable of reference type, the address of the object to which it points is compared For the equals method
If the equals method is not overridden, the address of the object pointed to by the variable of the reference type is compared;
Classes such as String and Date override the equals method by default, comparing the contents of the object they point to.
Note: The equals method cannot work on variables of the basic data type.
Precautions for Beijing Post OJ
-
Beijing Post supports c/c++/java7 (I choose java) -
When java submits code, remember to delete the package name, change the class name to Main, and the entry function is main(String[] args) ; -
Interface for submitting code: -
Check result interface: (wrong answer, no prompt!) -
Do not have Chinese comments, and Chinese encoding is not supported