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

nextInt()、nextFloat() Similar functions and next() Consistent characteristics.

  • 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.

Although there is one ending symbol for these two functions Enter n , but not the same:

  • 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

For example, what I entered first five In fact, the input is 5\n this \n As nextInt() Terminator, but \n It will not disappear if nextLine() Will be received.

To sum up There are three differences between the two input functions:

  • 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

OJ has one input: A B , that is, two inputs with a space between them.

This kind of input is very simple in c/c++ scanf("%d %d",a,b);

But java does not Format Input , can be used nextLine() Receive a row of data, and then use string.split(" ") Separate. It can also be used directly next() Receive twice because of a space pair next() That's the ending sign.

Multiple groups of data input, uncertain group number, end with EOF.

 while(sc.haveNext()){ // }

output

Mainly format 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));

Note that there is no line break in the last line of the OJ output sample, but actually there needs to be a line break.

Basic data type

int、float、double、char、String

String is not a basic data type. It should be a class.

The classes boxed by these basic data types correspond to Integer Float、Double、Character。

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

The ASCII code of the number 0 is 48, and the corresponding number of 9 is 57

Large A corresponds to 65, and small A corresponds to 97

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

This replacement and StringBuilder Class replacement methods are different, with two differences:

  • 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

It is used to iterate over the collection. If you are looping while deleting elements according to conditions, you must use an iterator, otherwise the deletion will be incorrect.

 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);

The output is:

 0|3 1|2 [*, *]

Why? Because after you delete it, the size of the set changes, and i keeps increasing.

Direct iterator:

 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

Iterator can be applied to all sets, including Set, List, Map and their subtypes. The ListIterator can only be used for List and its subtypes.

ListIterator has many useful methods:

 //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?

Need to override hashCode() and equals() method.

Here, you must ensure that the hashcodes of the two elements with equal equals are also equal. Otherwise, the set set does not consider these two elements to be the same, although the return value of equals is 1.

In List. remove (Object e); Actually, it only needs to be rewritten equals() One function is OK. Of course, according to the design plan, two elements are equal, and their hashcode() must also be equal. This is a convention. Avoid unnecessary problems caused by others using your code.

https://www.cnblogs.com/dolphin0520/p/3681042.html

set

Is Set really unordered in Java?

The advantage of set is that there are no duplicate elements. The construction method can also be seen above. You can directly convert the list to set

PriorityQueue

The java priority queue always outputs an element according to the specified rules every time peek() (the smallest is taken by default). But the queue is not orderly.

 //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

The stack is characterized by first in and then out.

Stack Inherited from Vector (Dynamic array, many methods are similar to list)

 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

Map is not a simple binary group. One of its characteristics is that keys cannot be repeated.

 //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

Let's briefly introduce:

  • Patten Receive regular expression as parameter
  • Matcher stay Matcher On the basis, receive strings as parameters

Split String

This method is the one I use most. Useful in processing some complex inputs

 //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 }

It can also output the position of the matching string in the original string.

https://blog.csdn.net/zengxiantao1994/article/details/77803960

ScriptEngineManager

This year, I saw the code of a big guy and found that JavaScript code can be called in Java and the results can be obtained. For example, an infix expression can be calculated directly with JavaScript... Amazing!

 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);

https://shift-alt-ctrl.iteye.com/blog/1896690

Data structure and algorithm

data structure

tree

Sequential storage structure of tree( Father representation )

https://www.ihewro.com/archives/895/#ProblemC This structure is used in this question.

This structure is very similar to the figure Critical matrix The writing method of. But this is a one-dimensional structure.

edges[child] = parent The value of each position is the parent node of the numbered node.

 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(); } } }

Mark here https://www.ihewro.com/archives/894/#ProblemC The recursive KILL method is worth learning.

Chain storage structure of tree

You can use the structure of the adjacency list of a graph( Child representation )

Binary tree

Binary linked list structure

https://www.ihewro.com/archives/904/# Binary sort tree This question uses the tree structure, builds the tree, and requires traversing before, during and after printing

 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

https://www.ihewro.com/archives/894/#ProblemD. network transmission

This problem uses adjacency matrix, and at the same time, finds the shortest path of the graph, using the Dijkstra algorithm.

 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

The heap is actually a binary tree.

algorithm

Dijestra shortest path

https://www.ihewro.com/archives/894/#ProblemD

Algorithm goal: find the shortest path from a source point O to all vertices

Main ideas

  • 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

Algorithmic process

  • 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

In a word, the whole process is: Constantly take the node with the shortest path from the source point to the T set as the intermediate point, and modify the shortest path of other nodes


When I was a beginner, I didn't understand the function of path [] array. In fact, this is a very ingenious way to store the path from the source point to the target node.

For example, the shortest path from vertex 0 to vertex 6 is 0-1-2-5-4-6
Path [6]=4. You only need to store the previous node number, not the serial number. This idea can also be used in our programming.

How can we find the complete shortest path from 0 to 6 through the path [] array?
path[6] = 4
path[4] = 5
path[5] =2
path[2] = 1
path[1] = 0
We save these in Stack Inside, it can be done after the stack is removed.


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.

Code section

The following code does not define the S set, because this set is actually useless in the algorithm.
T set I use java list Structure.
The graph is represented by the order structure of the adjacency matrix.

 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

https://www.ihewro.com/archives/893/#ProblemC

After watching Dijestra, I congratulate you. This algorithm process should be simpler.

Algorithm target: solve All nodes Shortest path to all other nodes

(The effect is equivalent to using Dijkstra algorithm for each node, but the time complexity of Freud algorithm is very high o (n ³))

Main ideas:

  • 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)

As you can see, there is no S set or T set. How to choose the middle point?

Algorithm process:

  • Take each vertex as an intermediate vertex, and then compare disti with disti+distk to determine whether to modify the shortest path.

code:

The critical matrix is still used as the storage structure of the graph.

 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

C++built-in full array algorithm, envy.

 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

Window>Preferences>Java>Editor>Content Assist

Put . Modify to .abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ(,

https://blog.csdn.net/ithomer/article/details/7090405

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

  1. Special examples were not taken into account, such as the first question of score addition in 2014 online research
  2. Copy past code without package name package bupt; He does not prompt for compilation errors, but the answer is an error
  3. First, determine whether you understand the question correctly
  4. Then test critical conditions, special conditions
  5. Runtime error: memory out of limit, not some array or collection data out of limit, but memory out of limit

Some precautions

  1. Pay attention to the variable initialization position. If it is written inside the loop and outside the loop, it is far from perfect
  2. 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.

    http://www.cnblogs.com/dolphin0520/p/3592500.html

Precautions for Beijing Post OJ

  1. Beijing Post supports c/c++/java7 (I choose java)
  2. When java submits code, remember to delete the package name, change the class name to Main, and the entry function is main(String[] args) ;
  3. Interface for submitting code:
  4. Check result interface: (wrong answer, no prompt!)
  5. Do not have Chinese comments, and Chinese encoding is not supported
Last modification: March 28, 2019
Do you like my article?
Don't forget to praise or appreciate, let me know that you accompany me on the way of creation.