need help with Java recursion
I've been asked to create a public method that does nothing but call another recursive method. The purpose of the second method is to search inside an array for Int values.
So far I have this:
int[] array = {1, 2, 3, 7, 8, 11, 20, 30, 50, 100};int cont = 0;public int searchI(int x) { searchR(x); return x;}private void searchR(int y) { if (cont < array.length) { if (array[cont] == y) { System.out.println(y); } else { searchR(cont++); } }}
However, it always prints the value of y no matter what number I use, whether there is one in the array or not. I'm still new to recursion and haven't quite grasped the essence of it yet. That's probably why my approach doesn't work The reason (besides it's wrong). Any ideas? and may help to better understand the term.
Solution:
As far as your code is concerned, it will output y when it finds y in the array for the following reasons:
if (array[cont] == y) { System.out.println(y);}
After the first call to searchR(x) it is searching for the value of cont instead of the value of x. Change searchR(cont) to
cont++; searchR(y);
If the position of the number you want to search for, use System.out.println(cont) instead of System.out.println(y).
int[] array = {1, 2, 3, 7, 8, 11, 20, 30, 50, 100};int cont = 0;public int searchI(int x) { searchR(x); return x;}private void searchR(int y) { if (cont < array.length) { if (array[cont] == y) { System.out.println(y); //System.out.println(cont); if you want the position as output } else { cont++; searchR(y); } }}
need help with Java recursion Related posts
- need help reading gromac files with Python
I have a gromac file from which specific details can be extracted. The file format is as follows. Only I need the values in each column.Generated by trjconv: a bunch of waters t = 0.00000 3000 1SOL OW 1 1.5040 2.7580 0.6820 1SOL HW1 2 1.4788 2.7853 0.7702 1SOL HW2 3 1.4640 2.8230 0.6243 2SOL OW 4 1. ...
- javascript - need help with dynamically creating radio buttons
I have a problem with setting the label and alignment of a dynamically created radio button, I want to retrieve a value from a textbox and use this value as the label for the newly generated radio button, I try to generate the radio button using this code but It doesn't give it a label (the one retr ...
- Need help with Java 8 flow logic
I have an array list containing multiple strings. I need to replace one item in that list based on certain conditions and keep the other strings. I need help to do the Java 8 way.Code example:String newPONumber ="Orig PO#: 22222222222222456";ListexistingMessages = Arrays.asList("Orig PO#: 2222222222 ...
- needs some help with regular expressions (php)
For example, I have the following code:$string ="adf gggg eere value aaaa bbb (10) value ddttt ggg www (20) value ddttt ggg www dddd (40)"; preg_match("/(value).*(\(\d+\))/is", $string, $result); var_dump($result[2]); // outputs 40.I want to get the first value (10). The above code output 40 is meaningful, but not what I want. The string pattern is: the word"value", then multiple any characters, and then"(", Integer,")". It seems that I am missing something obvious... I didn't do much work with ...
- python – (HOMEWORK) Need help with my grid recursive function
Ok, so I'm writing a program that will run through the grid and find the cavity. For each white cavity, it fills it with a color. As long as the white space next to this location is also white, it will It will continue to fill in the color until the space is blocked. Then it continues to scan until it finds a new white cavity. Here is an example of what the grid looks like: http://imgur.com/uDzzq. This is what it has been so far Code...x = 0 y = 0 if cave[row][col] != AIR: return if cave[row][co ...
- javascript-need help drawing charts with highcharts in angularjs
I have some data from elasticsearch, which has the start and time of the task. The end time of a specific agent task, which needs to be drawn horizontally on the chart, indicating the start and end time of that specific task. I tried to use the columnrange chart type but because I Unable to enter th ...
- python – need help accessing USB token with M2Crypto.Engine
I'm using M2Crypto-0.20.2. I want to use engine_pkcs11 from the OpenSC project and the Aladdin PKI client for token based authentication, xmlrpc calls over ssl.from M2Crypto import EngineEngine.load_dynamic()dynamic = Engine.Engine('dynamic')# Load the engine_pkcs from the OpenSC projectdynamic.ctrl ...
- java - need help with weird Class#getResource() issue
I have some legacy code that reads configuration files from existing jars, for example:URL url = SomeClass.class.getResource("/configuration.properties");// some more code here using url variableInputStream in = url.openStream();Apparently it worked before, but when I execute this code, the URL work ...
- java - need help with hashMap about expiry time limit
I need a thread safe Map with a time bound expiration policy. I tried to find an existing library, but couldn't find one. Jboss caching will be an important option for my requirements. I have a first cut draft. Please check it out Code posted on pastebinI need constructive comments and suggestions f ...
- need help with Java homework
I need some help with assignment assignment. My task is to create a program that creates a Till object, makes the payment, issues the exact change, tells me which coins I need to use, and then how many coins I need until afterward. The following is the code I wrote. The USmoney class is done and run ...
- need help with Java recursion
I've been asked to create a public method that does nothing but call another recursive method. The purpose of the second method is to search inside an array for Int values.So far I have this:int[] array = {1, 2, 3, 7, 8, 11, 20, 30, 50, 100};int cont = 0;public int searchI(int x) { searchR(x); retur ...
- php-I need help with OAuthException Code 2500
I am trying to develop a Facebook application (apps.facebook.com/some_app) using PHP and I need to provide some information based on the user's music interests. I found it under "user_likes>games".My question is as follows:In order to gain access, I have implemented the oauth dialog method suggested in the API of my index page.$auth_url = "http://www.facebook.com/dialog/oauth?client_id=" . $app_id. "&redirect_uri=" . urlencode($canvas_page) ."&scope=user_likes";> After successful ...
- java - need help with xPath expressions for namespaces
I need some help with xpath expressions.I have the following xml document:texthelloI am using Springs rest template to retrieve data.This is where I use the xpath expression to get the node value:xpathTemplate.evaluate("base:*", xmlSource, new NodeMapper() { public Object mapNode(Node node, int i) t ...
- java - need help with the process
When I start a process like process = Runtime.getRuntime().exec("gnome-terminal"); it starts executing the shell, I want to stop the shell execution and want to redirect I/O from the process, can anyone tell me to do this?My code is:public void start_process(){ try { process= Runtime.getRuntime().ex ...
- php-Need help with REST API (webservivice) for woocommerce checkout
How to use Woocommerce REST API to write a web service for checkout, including payment methods. Is it available for Woocommerce REST API? I am new to Woocommerce REST API. Any help is appreciated.Solution:You can refer to Woocommerce REST API Documentation for Woocommerce REST API development.For pa ...
- Cakephp 2: Need help with PDOStatement misconfiguration
I have a problem with a request to Cakephp 2. When I try to type ' or ? , in the string I get the error messageError: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound[17:05:44] Root: #0 /var/home/public_html/lib/Cake/Model/Datasource/DboSource.php(436): PDOStatement->execute(Ar ...
Recent Posts
- in Python, is time.time()*1000 accurate enough?
I want to capture the timestamp with sub-second precision in python. It seems that the standard answer is int(time.time()*1000)However, if time.time() returns a floating point number, will you encounter precision problems? There will be some values that cannot be accurately represented as floating p...
- is engaged in the work of programmers, Python big data, Java, front-end, which one has development prospects?
First of all, let me talk about big data. There are many training institutions that train big data. Based on my years of experience in the industry, the name big data sounds good, it seems to be very big. But the so-called training of "zero-based" people who have not done development to learn big da...
- java study notes of IO programming-byte stream and character stream
1. The basic concept of flowThe File class in the java.io package is the only program processing class related to the file itself, but File can only manipulate the file itself but not the content of the file, or the core meaning of IO operations in actual development lies in: input And output operat...
- python-Use sklearn GridSearchCV to find optimized parameters with big data (15750 samples)
I am trying to use GridSearchCV in sklearn in Python to find the parameters of the SVM classifier. The shape of the training data is (15750, 65536) (15750 samples, feature dimension: 65536).Everything works fine with the default settings! However, if I want to use the parallel processing option, by ...
- javascript-Tern: Use tern server to synchronize script resources
In JBoss Devstudio, I received Tern's new error"Error": Sync script resources with tern server. This is not a real error, but it is a process that happens every time I click a JavaScript file. It just rotates And freeze the entire IDE. This has never happened to me before, I was working on this proj...
- Machine learning programming exercise ex5 error
ex5 There is an error in learningCurve.m and validationCurve.m: There is a sentence in the pdf tutorial: It means that the regularization term should not be included when calculating the training error and the test error, that is, the lambda in the linearRegCostFunction should be equal...
- Python3---Crawler Post Passing Parameters
Preface Python3 Post parameter passing mainly uses data in the urllib.request.urlopen(url,data) parameter. The data parameter is mainly to set the parameters of the post. Modification time: 20191218 Astronomical alone     First of all, when planning to use...
- JavaScript-PDFKit: PNG unknown image format error
I am using the pre-built version of PDFKit in my browser, and when I try to add PNG, I get the following error:Uncaught Error: Unknown image PDFImage.open format.util.js:546 module.exports.image deflate.js:773 img.onload PDFrenderer.js:195I converted the image to PNG on the server (to crop it into a...
- Java source reading notes (2)-LinkedList
First, let's look at the initialization/** * Constructs an empty list. */ public LinkedList() { } /** * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * * @param c the collection whose elements are to be placed ...
- php-check Javascript and redirect it to another page
I want to check if Javascript is enabled. If it is enabled, the rest of the code will be displayed, but if it is disabled, it will be redirected to google.comNow, what to do? I am trying to write this code:Your browser does not support JavaScript!JS must be enabledthis code must be hidden when JS is...