I have this small block of code used to find the sum of certain numbers:
public class TestClass {
public static int sumOfNums(int num[], int int) {
if(int == num.length-1) return int;
else if( (num[int]%2==0) || num[int] <= 0 ) {
return num[int] + sumOfNums(num, int+1); }
else return 0 + sumOfNums(num, int+1);
}
public static void main(String[] args) {
int[] arr = {-2,0,8,4,5,6,10,-5,-2,7,9};
System.out.println(sumOfNums(arr, 0));
}
}
However, whenever I run the print statement I get the exception:
Exception in thread "main" java.lang.StackOverflowError
at TestClass.sumOfNums(TestClass.java:13)
at TestClass.sumOfNums(TestClass.java:10)
Can anybody help me?
As another user said, your recursion is never ending.
Changing arr[head-1] to head-1 should fix this problem on this line:
else return 0 + sumNegEven(arr, arr[head-1]);
and changing it here as well:
return arr[head] + sumNegEven(arr, arr[head-1]); }
public class TestClass {
public static int sumNegEven(int arr[], int head) {
if(head == 0) {
return 0;
} else if( arr[head]%2==0 || arr[head] <= 0 ) {
return arr[head] + sumNegEven(arr, head-1);
} else {
return 0 + sumNegEven(arr, head-1);
}
}
public static void main(String[] args) {
int[] arr = {-2,0,8,4,5,6,10,-5,-2,7,9};
System.out.println(sumNegEven(arr, arr.length-1));
}
}
By call calling the arr[head-1] you were calling value of the index not index and they last long because recursion is not terminated. If you calling head-1, you are calling actual index and will get answer 21 without exception.
this won't process the first item in the array
if(head == 0) {
return 0;
}
you will have to change it to
if(head < 0) {
return 0;
}
Related
I'm using recursion to solve the problem. On paper my answer should work so I went wrong with the code. However, I can't figure exactly where the problem is.
public class Partition {
public static void main(String[] args) {
System.out.println(part(6,4));
}
public static int part(int n, int m) {
if (n==0) {
return 1;
}
else if(m == 0 || n<0) {
return 0;
}
else {
return part(n-m, m) + part(n, m);
}
}
}
You need to reduce m only for the problem to return 9 as you indicated.
public static int part (int n, int m) {
if (n == 0) {
return 1;
} else if (m == 0 || n < 0) {
return 0;
} else {
return part(n - m, m--) + part(n, m);
}
}
I'm not sure what you're trying to do, but if it is to compute the combination it should look like this :
public static int part(int n, int m) {
if(m>n) { //This prevent a wrong input from the user
return part(m, n);
} else if (m==0 || m==n) { //This is your base case
return 1;
} else if(m < 0 || n<0) { //this should not happened, but you never know
return 0;
} else { //this is where you're making mistake(s)
//I don't know if I'm using the formula you are looking for
//But if not, make sure yours do not use part(n, m) otherwise it will run forever
return part(n-1, m) + part(n-1, m-1);
}
}
I have to write a recursive method in Java that returns true if a row is descending and false it does not.
This is what I tried, but it doesn't work properly:
ArrayList<Integer> getallen = new ArrayList();
getallen.add(500);
getallen.add(400);
getallen.add(300);
getallen.add(200);
getallen.add(100);
getallen.add(0);
System.out.println(isDescending(getallen));
}
public static boolean isDescending(ArrayList<Integer> getallen) {
if (getallen.size() >= 2) {
if (getallen.get(0) < getallen.get(1)) {
return false;
} else if (getallen.size() > 0) {
getallen.remove(0);
return isDescending(getallen);
} else {
return true;
}
} else {
return false;
}
}
I think you have unnecessary cases if the size is less than 2 you can only assume true.
Try:
public static boolean isDescending(ArrayList<Integer> getallen) {
if (getallen.size() >= 2) {
if (getallen.get(0) < getallen.get(1)) {
return false;
} else {
getallen.remove(0);
return isDescending(getallen);
}
} else {
return true;
}
}
If I had to grade this, it would get a big fat X for
Having been fraudulently asked on stackoverflow
Being quite inefficient (try running this test on a list of a million elements, then realise that removing element 0 in an ArrayList causes all elements to shift down)
Instead consider:
public static boolean isDescending(List<Integer> getallen) {
return isDescending(getallen, 0);
}
public static boolean isDescending(List<Integer> getallen, int from) {
return from >= getallen.size() - 1
|| getallen.get(from) < getallen.get(from + 1)
&& isDescending(getallen, from + 1);
}
How about little bit more efficient approach with logarithmic recursion depth? Just as an exercise.
public static void main(String[] args) {
List<Integer> getallen = new ArrayList<Integer>();
getallen.add(500);
getallen.add(400);
getallen.add(300);
getallen.add(200);
getallen.add(100);
getallen.add(0);
System.out.println(isDescending(getallen));
}
public static boolean isDescending(List<Integer> getallen) {
return isDescending(getallen, 0, getallen.size());
}
private static boolean isDescending(List<Integer> getallen,
int start, int end) {
if (end - start <= 1)
return true;
if (end - start == 2) {
return getallen.get(start) > getallen.get(start + 1);
}
int middle = (start + end - 1) / 2 + 1;
return (getallen.get(middle - 1) > getallen.get(middle)) &&
isDescending(getallen, start, middle) &&
isDescending(getallen, middle, end);
}
I'm teaching myself about recursive calling of methods in java. I'm constantly getting StackOverFlowErroron my implementation:
public class LimitedRecursion {
public void m(int limit) {
if (limit == 0) {
System.out.println("finished2");
}
m(limit - 1);
}
}
i have set the limit to 42 in the main. Can someone point me to the right direction on this? Its supposed to terminate once limit == 0
This doesn't finish the recursion, since you don't exit the method when the condition is met, and you still make the next recursive call (m(limit - 1);) :
if (limit == 0) {
System.out.println("finished2");
}
m(limit - 1);
This will end the recursion :
if (limit == 0) {
System.out.println("finished2");
return;
}
m(limit - 1);
The correct recursion can be :
public class LimitedRecursion {
public void m(int limit) {
if (limit == 0) {
System.out.println("finished2");
} else {
m(limit - 1);
}
}
}
Something like this, Add a return statement
public static void main(String[] args) {
System.out.println(m(5));
}
public static String m(int limit) {
if (limit == 0) {
return "finished";
}
return m(limit - 1);
}
output
finished
I have a very easy question but I don’t know what. The sample code below
public class test {
public static void main(String[] args) {
test test = new test();
int temp = test.method(0);
System.out.println("temp = " + temp);
}
public int method(int i) {
if (i < 7) {
i++;
method(i);
}
return i;
}
}
If I want get 7 in the temp in the main what can I do? Just use the other static parameter? or is there any way to achieve this one?
public int method(int i) {
if (i < 7) {
i++;
return method(i);
} else {
return i;
}
}
should work fine :)
breakdown:
IF i is smaller than 7, increment i and return method(i)
ELSE return i (must be 7)
the else block is optional:
public int method(int i) {
if (i < 7) {
i++;
return method(i);
}
return i;
}
but it's more clear if you have the else since it is conditional.
Structure of my class:
public class Priorityy implement Comparable {
public int compareTo(Object pe) {
Priorityy p = (Priorityy) pe;
if (this.key < p.key) {
return 1;
} else if (this.key > p.key) {
return -1;
} else {
return 0;
}
}
}
Th problem is that p.key is always null, why exactly is that? I have my array initialized with elements in it but it always throws NullPointerException whenever I try Arrays.sort(arr).
How can I fix this?
Edit: Here is the complete code and print did print the elements of array arr:
import java.util.Arrays;
class Priorityy implements Comparable {
int size;
int front = 0;
int rear = 0;
static Priorityy[] arr = new Priorityy[3];
int key;
String value;
public Priorityy(int key, String value) {
this.key = key;
this.value = value;
insert();
}
public void insert() {
arr[front] = this;
System.out.println(arr[front].value);
while (front + 1 != 3) {
front = front + 1;
}
}
public Priorityy remove() {
Priorityy x = arr[front];
front = front - 1;
return x;
}
public int compareTo(Object pe) {
Priorityy p = (Priorityy) pe;
if (this.key < p.key) {
System.out.println(p.key);
return 1;
} else if (this.key > p.key) {
System.out.println("3");
return -1;
} else {
System.out.println("4");
return 0;
}
}
public static void main(String... s) {
new Priorityy(10, "Watch");
new Priorityy(40, "Laptop");
new Priorityy(60, "Wallet");
Arrays.sort(arr);
for (Priorityy element : arr) {
System.out.println(element.key);
System.out.println(element.value);
}
}
}
As per your code
Priorityy p = (Priorityy)pe;
^^ ---------- this is null
You have null object in the array. Handle null object gracefully.
For example
if(pe instanceof Priorityy){ // return false for null object
// your code goes here
}
Better use Generic Comparable and use Integer.compare(int,int) to compare two int values.
class Priorityy implements Comparable<Priorityy> {
public int compareTo(Priorityy pe) {
if (pe != null) {
return Integer.compare(this.key, pe.key);
} else {
// return what ever if pe is null
}
}
}
You're putting things into your array in a really strange manner.
But given that, the problem is that you're not using a static field to store the next position to insert an element into, so the next time you create an instance of Priorityy, the field first contains the value zero again. So you're inserting all three objects into element zero of the array.
Change one line of your code and it will work:
int front = 0;
To:
static int front = 0;
I don't see where you are using size and rear but you probably want these to be static too.
One other suggestion: Java has a nice short syntax for increasing or decreasing the value of a variable by one using the ++ or -- operator, so you can shorten things by saying:
front++;
instead of
front = front + 1;
(and front-- instead of front = front - 1)