return statement does not ending method java - java

public class Interpolation_search {
public static void main(String...s) {
int rr[]= {1,2,3,4,9,10,15,80};
System.out.println(search(rr,0,7,3));
}
static int search(int ar[], int lo, int hi,int X) {
if(lo<hi&&ar[lo]!=ar[hi]) {
int mid=lo + ((hi-lo)/(ar[hi]-ar[lo]))*(X-ar[lo]);
if(X==ar[mid])
return 1; //l1
else if(X>ar[mid])
search(ar,mid+1,hi,X);
else search(ar,lo,mid-1,X);
}
return 0; //l2
}
}
return is executing twice first at l1 and second at l2.

It seems that you have difficulties understanding recursion.
Your method search() is supposed to return an int result. And the method itself calls itself (using different arguments) repeatedly. Thing is: you are all ignoring these recursive calls.
In other words: the real answer is for you to step back and understand what recursion is meant to be, and how to properly use it. As a starter, you could try to change
search(ar,mid+1,hi,X);
to
return search(ar,mid+1,hi,X);

Related

recursion program to add and subtract a number

I want to implement this program but it throws errors on every function call and runs an infinite loop.
class abc
{
public static void main(String[] args) {
int n=16;
calll(n);
}
static int calll(int n)
{
if(n>0)
{
n=n-5;
calll(n);
return n;
}
else
{
n=n+5;
calll(n);
return n;
}
}
}
There is no end condition to your function.
Whether n is greater than 5 or not you run the calll function, which then runs the calll function again to infinite.
You need a conditon that will end the recursion, for instance changing the call function to this:
static int calll(int n)
{
if(n>0)
{
n=n-5;
calll(n);
return n;
}
else
{
return n;
}
}
However the function is still rather pointless as you don't actually do anything with n. Keep in mind that the n that you define in the main function is never modified.

Implement my own recursive version of the indexOf method

So I'm trying to write recursive method indexOf which returns the starting index of the first occurrence of the second String inside the first String (or -1 if not found).For example, the call of indexOf (“Barack Obama”, “bam”) would return 8. Also I know that String class has method IndexOf, but I don't want to use it.
So far this is my code:
public class MyClass {
public static void main(String[] args) {
}
public static int indexOf(String s, String t) {
return abc(s, t, 0);
}
public static int abc(String a, String b, int c) {
if ((a.length() - c) < b.length()) {
return -1;
} else if (b.equals(a.substring(c, c + 3))) {
return c;
} else {
}
}
}
It depends how much of the library you want to use.
One option is:
int indexOf(String container, String text, int index) {
//Too short container
if (container.length() < text.length()) return -1;
//found
else if (container.startsWith(text)) return index;
//keep searching
else return indexOf(container.substring(1), text, index+1);
}
indexOf("banana", "nana", 0) == 2;
If you don't want to use .startsWith, then you need to implement your own version. A very good exercise would be to try and do this without ever using the .substring method, which is terrible (as it creates a copy of the string, O(n) space/time performance), and which is not needed for this task (use .charAt)
You can also split the official method indexOf from its recursive call that includes the index for more clarity).
You should think carefully about edge cases too :)

Java: Recursively search an array for an integer given an array, integer, and array length

I'm trying to write a recursive method that accepts an int array, number of elements in the array, and an integer, and returns whether the integer is present as an element in the array.I just can't figure out why I this isn't working for all my test cases. Any help would be much appreciated!
public static boolean search(int[] findIn, int target, int len){
if(len == 0){
return false;
}else if(findIn[len-1] == target){
return true;
}else{
return search(findIn, target, len-1);
}
}
Yes I realize there are better ways other than recursion to do this, but it is required that I do it this way.
My main method looks like this: I'm just hard-coding it for the time being:
int[] arr = {1};
System.out.println(search(arr,1,1));
Testcases:
I am almost certain, that your method parameters are in the wrong order:
Your results hint that you switched the 2nd and 3rd parameter!
Maybe this
static boolean search(int[] findIn, int target, int len)
should actually be
static boolean search(int[] findIn, int len, int target)
From what I can see, that code should work fine so I suspect your problem lies in your test cases rather than here.
One thing I will mention is that use of if-return-else constructs tend to complicate your code unnecessarily.
It's usually better to avoid that with something like:
public static boolean search(
int[] findIn, int target, int len)
{
if (len == 0)
return false;
if (findIn[len-1] == target)
return true;
return search(findIn, target, len-1);
}
I find that a lot easier to follow at a glance than trying to track what if clause I happen to be in at any given moment.
In any case, both it and your version perform fine, at least for small test cases. The first time you pass in a ten-million-element array is probably when you'll discover it's not the best poster child for recursion.
I tried something like this and it is working..
I am using a static instance variable to find the position of number in array.
In stead of returning the position of number you can modify to return a boolean
public class RecSearch {
static int pos=0;
public static void main(String[] args) {
int a[] = {1};
System.out.println(recSearch(a, 0));
System.out.println(recSearch(a, 1));
}
public static int recursiveSearch(int[] arr, int numtoSearch) {
if (pos>=arr.length) {
pos=0;
return -1;
}
if (arr[pos]==numtoSearch)
return (pos+1);
else {
pos++;
return recursiveSearch(arr, numtoSearch);
}
}
}
public class Solution {
public static boolean checkNumber(int input[], int x) {
return check(input,x,0);
}
public static boolean check(int input[],int x,int start){
if(start==input.length)
return false;
if(input[start]==x)
return true;
return check(input,x,start+1);
}
}

Understanding Java methods

So, I'm very new to Java, I have a summer college course and we're on functions or methods and I'm having a bit of trouble understanding them.
There is a question on a lab I'm having a little trouble with:
"Write a method called MaxOfThree that accepts three integer
parameters and returns the largest of the three."
This is what I have so far but I'm not sure whats wrong. I added the print statement at the end because I wasn't getting a return value when I ran it but now I'm getting errors and it's not compiling. If you could help me understand methods a bit more I'd greatly appreciate it. For instance how the parameters work and calling it and if what's included in the function call is correct and how that works. I just get so confused when I read through the material and was hoping for an explanation in more layman's terms. Thanks for any help, here is what I have so far.
public class Test {
public static void main(String[] args) {
int a = 2, b = 3, c = 4;
int maxValue = max3(a, b, c);
}
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
return max;
System.out.println(max);
}
}
Here are the errors I'm receiving just in case...
Test.java:16: error: unreachable statement
System.out.println(max);
^
Test.java:17: error: missing return statement
}
^
2 errors
You can't have a statement after the return statement, or to be more exact - a statement imediatelly after a return statement (such as your println) can never be executed, and is therefore an error.
The println should be before the return statement.
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println(max);
return max;
}
I suggest You to change those if statements into one simple for loop with simple int[] vector. This solution is much more elegant and flexible. Additionally, You initialized and not used anywhere int maxValue = max3(a, b, c); in Your code.
public class Demo {
public static void main(String args[]) {
int[] numbers = new int[] {2, 3, 4};
System.out.println(maxValue(numbers));
}
public static int maxValue(int[] n) {
int max = n[0];
for (int i = 1; i < n.length; i++) {
if (n[i] > max) {
max = n[i];
}
}
return max;
}
}
But let's bow for a moment on the problem of methods implementation in Java.
At the begining of Your journey through the vastness of the Java realm You should get familiar with two types of methods: 1) void methods, and 2) return methods. The first ones are responsible for doing something without returning any value. We can for example use them for setting values of the fields of our application, initializing GUI, or other operations. The use of the void method can look like this:
/* method declaration */
void setValue(int value) {
someField = value;
}
/* method invocation */
setValue(5);
After invocation of setValue(5) the value of the someField object will be 5. However, you have to remember about type compatibility, so in this case someField can not be e.g of String type.
Second method type mentioned above, i.e return method is very useful, when you expect the method to give You an output, e.g in result of some operations conducted on the data You've given to Your method. But of course it's not necessary, to provide for the return method an input. Anyway, the use of return method can look like this:
/* method returns text You've given to it */
String getText(String text) {
return text;
}
/* method returns result of addition of three given int's */
int calculate(int a, int b, int c) {
return a + b + c;
}
/* method return a random number */
int createRandomNumber() {
Random random = new Random();
return random.nextInt();
}
You can easily see, that there is plenty of space for improvisation. Basicaly and in summary, void methods can work with given objects, for example can set values and conduct other operations, but thay don't return any STRAIGHT results You can work with. Return methods, from the other hand, provide You physical results, which You can use in further operations, or even in other methods, for example:
import java.util.Random;
public class Demo {
private static int someValue;
public static void main(String args[]) {
setValue(calculate(
createRandomNumber(),
createRandomNumber(),
createRandomNumber()));
System.out.println(someValue);
}
public static void setValue(int value) {
someValue = value;
}
public static int calculate(int a, int b, int c) {
return a + b + c;
}
public static int createRandomNumber() {
Random random = new Random();
return random.nextInt();
}
}
The problem is that the compiler detects that execution will never reach the System.out.println line, so it refuses to compile. The line return max; effectively ends the method, so nothing more will run after that.
You should move return max; to below the System.out.println line.
Swap your last 2 lines (return and System).
It should be like this, return max statement should be the last line in your method if you want to print something, because return statement goes back or invoke the line that called him,so your print statement is not reach.
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println(max);
return max;
}
You need to put
System.out.println(max);
before:
return max;
the reason is your return unconditionally ends the function and therefore the compiler won't reach the println causing a compile error.
You have a System.out.println() statement after the return. return ends the method and so the System.out.println() will never happen because the method will have ended. That's why you are getting errors. Put the System.out.println() before the return:
public static int max3(int a, int b, int c) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println(max);
return max;
}
As already been said, after you return something, the method will end. So your output in the last line of the method will not be executed, so remove it.
You can print the returned value of the method when you write the following outside of the method:
System.out.println("highest value:" + max3(a,b,c));
So now, the 3 values are given to the method which can do something with them now. After it did the calculations, the method returns a value, which can now be printed to the console for example.
The issue with the code you provided is that you're trying to print to the console, after you use your return statement. This causes your program to never reach that line: System.out.println(max);

Keeping count in a recursive Java method

Here's what I'm trying to accomplish with this program: a recursive method that checks if the number of instances of a substring matches a specified amount of instances, returning a boolean.
Here's the issue I'm having with this particular recursive method: I'd like to be able to move the counter inside the recursive method body, however, I ran into the issue that the counter resets at each recursive call when it is in the method body. The only way I have been able to make it work is through the use of a static counter variable declared outside of the function body. Is there any other technique I can marshall in order to be able to situate the counter of the method in the method body so that this method may act as a "black box"?
Thanks for any advice or insights you can provide.
public class strCopies {
//count instances of part and whole equality
static int count = 0;
public static boolean copies(String whole, String part, int check)
{
//check if current string length is valid
if(whole.length() < part.length())
{
//check if check parameter equals part instances
if(count == check)
{
return true;
}
else
{
return false;
}
}
//check if current string value is an instance of part
if(whole.substring(0, 3).equals(part))
{
count++;
}
//recursive call
return copies(whole.substring(1), part, check);
}
public static void main(String[] args)
{
System.out.println(copies("dogcatdog", "cat", 2));
}
}
You are almost there: you should change the meaning of the check variable to the remaining number of matches, rather than the original number requested. Then you can rewrite the method without keeping an additional count at all, as follows:
public static boolean copies(String whole, String part, int check)
{
//check if current string length is valid
if(whole.length() < part.length())
{
//check if check parameter equals part instances
if(check == 0)
{
return true;
}
else
{
return false;
}
}
//check if current string value is an instance of part
if(whole.substring(0, 3).equals(part))
{
check--;
}
return return copies(whole.substring(1), part, check);
}
You can pass the count as an argument to the recursive function, this way it will not be "reset" when the method is called.
public static boolean copies(String whole, String part, int check, int count)
{
//check if current string length is valid
if(whole.length() < part.length())
{
//check if check parameter equals part instances
if(count == check)
{
return true;
}
else
{
return false;
}
}
//check if current string value is an instance of part
if(whole.substring(0, 3).equals(part))
{
count++;
}
//recursive call
return copies(whole.substring(1), part, check, count);
}
public int countRecursive(String whole, String part){
if(whole.length() < part.length()) return 0;
if(part.length()==0) return -1; // ints can't express "Infinity"
// maybe you want to return -1 only if whole is not null, and something else if it is.
int count = 0;
if(whole.substring(0, part.length()).equals(part))
count = 1;
return countRecursive(whole.substring(1), part) + count;
}
public boolean count(String whole, String part, int check){
return countRecursive(whole, part) == check;
}
Note that this does away with the counter at the expense of creating a whole bunch of strings for each state. (You replace a single int with the length of each string given.) But then again, if you want performance then you shouldn't be using recursion for something like this. A simple for loop would do much nicer.
You could add the counter to the method parameters as follows:
public class strCopies {
public static boolean copies(String whole, String pargs, int check){
return copies(whole, pargs, check, 0);
}
public static boolean copies(String whole, String part, int check, int count)
{
//check if current string length is valid
if(whole.length() < part.length()) {
//check if check parameter equals part instances
if(count == check) {
return true;
}
else {
return false;
}
}
//check if current string value is an instance of part
if(whole.substring(0, 3).equals(part)) {
count++;
}
//recursive call
return copies(whole.substring(1), part, check, count);
}
public static void main(String[] args) {
System.out.println(copies("dogcatdog", "dog", 2));
}
}
The simple version:
Create a class that contain the counter.
Initialize it on your main.
Pass its reference to the function.
Another idea:
Create a singleton class with a static counter and your function X.
Inside its constructor add one to its counter and call function X.
Then instead of running your function like you did before, "create" that class, thus increasing the counter and calling the function.
The neat thing is you can inherit that class and redefine X to whatever you choose at a latter stage, so you get this general class that counts on each activation of a function.
Not sure what is your recursive method doing. However, to maintain a counter, you can pass it as an argument to your recursive method.
public boolean copies(String whole, String part, int check, int count) {
// your code here....
if(whole.substring(0, 3).equals(part))
{
count++;
}
//recursive call
return copies(whole.substring(1), part, check, count);
}
When you make first call to your copies method, you'll need to pass 0 to your count.

Categories