Today, the Java language is a more common method, recursive method.
Definition of recursion
Simply put, the recursive method is "call yourself", through the recursive method can often be a big problem simplification, eventually compressed to an easy to deal with the degree. For programming, each recursive will reduce the amount of data;
Recursive patterns in Java
The beginning of each recursive function must be a statement that determines whether a recursive end condition is satisfied (usually an if statement); The function body must have at least one sentence of "Call yourself". Each recursive function must have a variable that controls recursion that can be terminated (usually as a function parameter). Each time you call yourself, the variable changes (usually smaller) and is passed to the called function.
The following is a recursive implementation of the factorial of a simple program
Public Static void Main (String args[]) { int n=8; int x; X=demo (n); SYSTEM.OUT.PRINTLN (x); } Public Static int demo (int n) { int y; Y=demo (n-1) *N; return y; }}
The program can only simply implement the recursion of the entered number, you can change the above into the form of the user's own input to achieve recursive results; (There are multiple user input methods are not involved)
The Hanoi tower problem seems simple, but it takes a lot of time to think, and it's hard to accomplish it if we don't adopt recursive method.
The topic is roughly like this: there are three adjacent pillars, labeled a,b,c,a pillars from bottom to top by pyramid-shaped stack of n different size of the disc, to move all the plate one to the pillar C, and each move on the same pillar can not appear on the large plate on the top of the small plate, ask at least how many times to move
And then we'll analyze the problem.
1. If there is a disc on a, move the disc directly to C
2. If there are N discs, move the front n-1 disk first to B, and then move yourself to the C
So this problem can be achieved in 3 steps.
1. Transfer the n-1 disc on a to Tower B using the C tower
2 Put the rest of the disc on C.
3. Place the n-1 disc on B onto the C drive with a disc
The following is the implementation of the Code
ImportJavax.swing.JOptionPane; Public classHannuo { Public Static voidMain (String args[]) {string W=" "; W=joptionpane.showinputdialog ("Please input Panzishu"); intJ=0; CharA= ' A ', b= ' B ', c= ' C '; J=Integer.parseint (W); Move (J,A,B,C); } Public Static voidMoveintMCharACharBCharc) {if(m==1) {Joptionpane.showmessagedialog (NULL, A + "," +c, "", Joptionpane.plain_message); } Else{Move (M-1, a,c,b); Joptionpane.showmessagedialog (NULL, A + "," +c, "", Joptionpane.plain_message); Move (M-1, B,a,c); } } }
Implementation of recursion in Java and implementation of Hanoi using recursive method