search
HomeComputer TutorialsComputer KnowledgeNot familiar with Java recursive method code

Not familiar with Java recursive method code

java code does not understand recursive methods

This is also a loop method. It may be difficult for beginners to understand... Let me explain

For example, the parameter in the fun() method is 100. Let me change it to 2.

The purpose of this recursive method is accumulation. The result is the same as the loop accumulation, but the execution method is different.

The process of program execution is as follows:

When you pass 2 in, the program will execute the content in else

That is return temp fun(temp-1);

The actual return is: 2 fun(2-1);

That is: 2 fun(1) changes the original parameter 3 to 2;

Let me start. This is an accumulation program, so take out 3 and assign it to the sum defined before, so the current sum=2;

Because this is a recursive method, the fun(int temp) method needs to be executed repeatedly;

It’s just that the parameter now becomes 1

So the next step will be like this:

Because the parameter is 1, it will enter the if

So it will return 1;

So the current sum should be the previous sum plus the 1 returned by the current fun(1)

so.....now sum should be: 2 1=3;

I just cited the cycle between two numbers. The cycle between the other 98 numbers is also like this

In short, recursion means to keep calling yourself until the conditions cannot be met, then it will not call itself.

Take a look, it may be a bit much. I want to explain it more clearly. I have encountered it before, but I have never asked anyone else. If you don’t understand or don’t understand, ask me again...

Java Recursive Algorithm If you have high income, please come in! Use recursion to implement

The work is very beautiful. If you can make an interface of this level, this small problem should not be difficult for you.

The question here is:

1. To design the structure of this graph, the easiest way is to use an array.

2. How to enumerate connected nodes. Simply put, it is a question of judging upper left, upper right, left, right, lower left, and lower right.

3. How to determine the same color in sequence? The simplest algorithm is the flooding method. Just start looking from the 6 directions above. After finding the next point, start looking from the 6 directions. . .

The approximate code is as follows:

class Rabbit

{

final int D_UP_LEFT = 1 ;

final int D_UP_RIGHT = 2;

final int D_LEFT = 3;

final int D_RIGHT = 4;

final int D_DOWN_LEFT = 5;

final int D_DOWN_RIGHT = 6;

getColor () ;

getCloseRibbit (int direction)

{

... // Here is the function to obtain adjacent rabbits in the specified direction

// If not return null .

}

int getColor () {}

List checkColor ()

{

ArrayList list = new ArrayList () ;

doCheckColor (list, this) ;

return list ;

}

void doCheckColor (List list, Rabbit r)

{

if (r.getColor () != this.getColor () || list.contains (r))

return ;

list.add (this) ;

for (int i = D_UP_LEFT ; i

{

Rabbit next = r.getCloseRibbit (i) ;

if (next != null)

next.doCheckColor (list, r) ;

}

}

}

The resulting list is the bunny of the same color you want.

How does JAVA use the recursive method to get nn from 1 to m

Recursion using arrays:

public class Test12 {

static int M = 4;

static int N = 3;

static int[] a= new int[]{1,2,3,4};

static int[] b = new int[N];

public static void main(String[] args){

C(M,N);

}

static void C(int m,int n){

int i,j;

for(i=n;i

b[n-1] = i-1;

if(n>1)

C(i-1,n-1);

else {

for(j=0;j

System.out.print(a[b[j]] " ");

System.out.println();

}

}

}

}

Output:

1 2 3

1 2 4

1 3 4

2 3 4

java implements recursive operation n! If n is not an integer, you will be prompted to re-enter

java implements recursive operation n! , enter n, if it is not an integer, you will be prompted to re-enter...

port java.util.Scanner;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Test {

public int jiecheng(int num) {// Recursive factorial

if (num > 1)

return num * jiecheng(num - 1);

else if (num == 1)

return 1;

else

return 0;

}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in); // Get input from the keyboard

String num = """;

Pattern p = Pattern.compile("\\d "); // Regular expression, matching (1 to N digits) integer

Matcher m = null;

int k = 0;

while (true) {

System.out.print ("Please enter an integer:");

num = sc.nextLine(); // Get a line of input

m = p.matcher(num);

if (m.matches()) {

k = Integer.valueOf(num); // Convert string to integer

break;

} else

System.out.println ("Not an integer, please re-enter!");

System.out.println();

}

System.out.println(new Test().jiecheng(k)); //Call factorial method

}

}

Happy to live in a treasured land and prosper for thousands of years. May everything be prosperous for your family and your family. Happy to welcome the new year

The above is the detailed content of Not familiar with Java recursive method code. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Excel办公网. If there is any infringement, please contact admin@php.cn delete
How to Solve Windows Error Code "INVALID_DATA_ACCESS_TRAP" (0x00000004)How to Solve Windows Error Code "INVALID_DATA_ACCESS_TRAP" (0x00000004)Mar 11, 2025 am 11:26 AM

This article addresses the Windows "INVALID_DATA_ACCESS_TRAP" (0x00000004) error, a critical BSOD. It explores common causes like faulty drivers, hardware malfunctions (RAM, hard drive), software conflicts, overclocking, and malware. Trou

ENE SYS Maintenance: Tips and Tricks to Keep Your System Running SmoothlyENE SYS Maintenance: Tips and Tricks to Keep Your System Running SmoothlyMar 07, 2025 pm 03:09 PM

This article provides practical tips for maintaining ENE SYS systems. It addresses common issues like overheating and data corruption, offering preventative measures such as regular cleaning, backups, and software updates. A tailored maintenance s

5 Common Mistakes to Avoid During ENE SYS Implementation5 Common Mistakes to Avoid During ENE SYS ImplementationMar 07, 2025 pm 03:11 PM

This article identifies five common pitfalls in ENE SYS implementation: insufficient planning, inadequate user training, improper data migration, neglecting security, and insufficient testing. These errors can lead to project delays, system failures

How do I edit the Registry? (Warning: Use with caution!)How do I edit the Registry? (Warning: Use with caution!)Mar 21, 2025 pm 07:46 PM

Article discusses editing Windows Registry, precautions, backup methods, and potential issues from incorrect edits. Main issue: risks of system instability and data loss from improper changes.

Discover How to Fix Drive Health Warning in Windows SettingsDiscover How to Fix Drive Health Warning in Windows SettingsMar 19, 2025 am 11:10 AM

What does the drive health warning in Windows Settings mean and what should you do when you receive the disk warning? Read this php.cn tutorial to get step-by-step instructions to cope with this situation.

How do I manage services in Windows?How do I manage services in Windows?Mar 21, 2025 pm 07:52 PM

Article discusses managing Windows services for system health, including starting, stopping, restarting services, and best practices for stability.

which application uses ene.syswhich application uses ene.sysMar 12, 2025 pm 01:25 PM

This article identifies ene.sys as a Realtek High Definition Audio driver component. It details its function in managing audio hardware, emphasizing its crucial role in audio functionality. The article also guides users on verifying its legitimacy

why won't driver asio.sys loadwhy won't driver asio.sys loadMar 10, 2025 pm 07:58 PM

This article addresses the failure of the Windows asio.sys audio driver. Common causes include corrupted system files, hardware/driver incompatibility, software conflicts, registry issues, and malware. Troubleshooting involves SFC scans, driver upda

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools