Why does this code give a StackOverflowError - java

I'm writing a method which is calculating the formula (x+y)/z if every variable's value is greater than zero. If they're smaller than zero the console should print "0".
My code looks like this:
package arrayTest;
public class berechne {
public static int berechneZahlen (int x, int y, int z) { //method
int ergebnis=0;
if (berechneZahlen(x, y, z) > 0) {
ergebnis = (x+y)/z; //ergebnis = result
}
else {
System.out.println("0");
}
return ergebnis;
}
public static void main(String[] args) {
System.out.print(berechneZahlen(2, 3, 6));
}
}
Now, in the editor I don't get any error. Everything seems fine. But when I'm compiling it, it gives me this error a dozen times:
Exception in thread "main" java.lang.StackOverflowError
at arrayTest.berechne.berechneZahlen(berechne.java:7)
at arrayTest.berechne.berechneZahlen(berechne.java:7)
at arrayTest.berechne.berechneZahlen(berechne.java:7)
I couldn't figure it out why the code isn't working properly.

You're calling your function recursively without termination point, so it cause StackOverFlowError
if (berechneZahlen(x, y, z) > 0)
Instead, introduce your code to check for x, y, x > 0 to match your requirement:
if every variable's value is greater than zero. If they're smaller than zero the console should print "0".
if (x > 0 && y > 0 && z > 0) {
//bla bla
} else {
//print 0
}

The method calls itself recursively. Try this:
public static int berechneZahlen (int x, int y, int z) { //method
int ergebnis=0;
if (z>0 && (x+y) > 0) {
ergebnis = (x+y)/z; //ergebnis = result
}
else {
System.out.println("0");
}
return ergebnis;
}

there are a couple of things wrong but also some things that can be improved.
what causes the error is that you are not checking if x,y,z is bigger than 0 but you are checking if berechneZahlen of those numbers is bigger than 0 which causes it to be called recursivly.
Furthermore in the case of one of them being 0 you are printing "0" in the method but you are also printing the result of berechneZahlen in your main function, resulting in "0" being printed twice, so you probably only want to return 0 in that case and not print it in the function itself.
Finally, I would also remove your ergebnis variable. It's not wrong but it's not necessary. you could simply just return the result.
This would then be your final result
public static int berechneZahlen (int x, int y, int z) {
if (x > 0 && y > 0 && z > 0) {
return (x+y)/z;
} else {
return 0;
}
}
But it can even be made shorter using a ternary operation like this
public static int berechneZahlen (int x, int y, int z) {
return (x > 0 && y > 0 && z > 0) ? (x+y)/z : 0;
}

The StackoverflowError is caused by a recursive call. That means the method berechneZahlen() is calling itself. In that call it is calling itself again and in that next call it is calling itself again and so on..
public static int berechneZahlen (int x, int y, int z) {
...
if (berechneZahlen(x, y, z) > 0) { // (fatal) recursive call here
...
}
Each single call allocates space on your computers memory until the memory is completely filled up with data and there is no more space left. In this moment the program execution breaks down, because it needs to allocate more space to work, but it can't allocate more.
Here is a working solution for you, where the recursion has been removed:
public class berechne {
public static int berechneZahlen (int x, int y, int z) {
if (x < 0 || y < 0 || z < 0) {
return 0; // return 0, if one of the numbers is below zero
}
return (x+y)/z; // return normal calculated result
}
public static void main(String[] args) {
System.out.print(berechneZahlen(2, 3, 6));
}
}

Related

How to print each number of a given number separately?

I have a code is written that is supposed to print each of the numbers separately. Heres an example.
printDigits(1362) prints
2
6
3
1
printsDigits(985) prints
5
8
9
You can pull apart a number into its digits using / 10 and % 10.
I have started some code the way I was taught but I am not sure what to do with the other variables.
Please have a look:
public class Main {
public static void main(String[] args) {
System.out.println(printDigits(1362));
System.out.println(printDigits(985));
}
public static int printDigits(int x){
int y = x % 10;
while (x > 0){
x = y;
System.out.println(x);
x = x / 10;
}
return x;
}
}
Why don't you convert the parameter x to String then read each Char in the String since a String is array of Char. If the output must be an int you convert the Char to int.
printDigits method should be like this:
public static void printDigits(int x) {
int y;
while (x > 0) {
y = x % 10;
System.out.println(y);
x = x / 10;
}
}
And the calling of the method will be like this:
printDigits(1362); // without the System.out.println()
There are various ways to achieve such results. You can better understand all solutions in these answers.
public static void printDigits(int num) {
while(num>0) {
int remainder = num%10;
num = num/10;
System.out.println(remainder);
printDigits(num);
}
}
You can use recursion to make it even more efficient.
You need to write int y = x % 10; inside the loop to "pull apart" every digit and print the digit y you have "pulled out".
Remove the System.out.println around your function calls.
You don't need to return a number, so you can change your return type to void:
public class Main {
public static void main(String[] args) {
printDigits(1362);
System.out.println();
printDigits(985);
}
public static void printDigits(int x) {
while (x > 0) {
int y = x % 10;
System.out.println(y);
x = x / 10;
}
}
}

More elegant inner methods declarations (without all the clutter)?

I have a recursive method that computes x^n with a certain algorithm, but this is of no importance here. What matters is my helper function which keeps track of recursive calls of this algorithm.
public class FastPot {
public static double fastPotRek(double x, int n) {
class Aux {
private double aux(double x, int n, int c) {
if (n == 0) {System.out.print("It took "+c+" recursive calls to compute "); return 1;}
else return (n % 2 == 0) ? aux(x*x, n/2, c+1)
: x * aux(x, n-1, c+1);
}
}
Aux a = new Aux();
return a.aux(x, n, 0);
}
}
To organize that somewhat I wanted to declare aux inside fastPotRek, and for that you have to use an inner class, whose methods I can't declare static. Because of this I instantiate Aux a = new Aux(); to be able to call aux.
Please tell me there is a way to make this more elegant and show me what I have overlooked... Like beeing able to make aux static somehow or not needing to instantiate Aux.
No need for inner class and no need to make that static as well:
public class FastPot {
//Static, use only from within FastPot
private static double aux(double x, int n, int c) {
if (n == 0) {
System.out.print("It took "+c+" recursive calls to compute ");
return 1;
} else {
return (n % 2 == 0) ? aux(x*x, n/2, c+1)
: x * aux(x, n-1, c+1);
}
}
}
//Your outward interface
public static double fastPotRek(double x, int n) {
return aux(x, n, 0);
}
}
Or if you insist on using an inner class:
public class FastPot {
//Static, use only from within FastPot
private static class Aux {
private static double aux(double x, int n, int c) {
if (n == 0) {
System.out.print("It took "+c+" recursive calls to compute ");
return 1;
} else {
return (n % 2 == 0) ? aux(x*x, n/2, c+1)
: x * aux(x, n-1, c+1);
}
}
}
//Your outward interface
public static double fastPotRek(double x, int n) {
return Aux.aux(x, n, 0);
}
}
I'll post this answer although many people (including me) will not be happy with this. Please don't use this kind of code:
public static double fastPotRek(double x, int n) {
return new Cloneable() {
private double aux(double x, int n, int c) {
if (n == 0) {System.out.print("It took "+c+" recursive calls to compute "); return 1;}
else return (n % 2 == 0) ? aux(x*x, n/2, c+1) : x * aux(x, n-1, c+1);
}
}.aux(x, n, 0);
}
Again, i highly suggest to use a private static method like:
public static double fastPotRek(double x, int n) {
return aux(x,n,0);
}
private static double aux(double x, int n, int c) {
...
}
You have this:
Aux a = new Aux();
return a.aux(x, n, 0);
I would write it like this (Does the same):
return new Aux().aux(x, n, 0);
Edit: I´m done with StackOverflow. You guys don´t want help? I won´t give it. From now on, I will only ask about MY problems, and won´t answer.

What does the method prod() do in this Java program?

public class Prod {
public static void main(String[] args) {
System.out.println(prod(1, 4));
}
public static int prod(int m, int n) {
if (m == n) {
return n;
} else {
int recurse = prod(m, n-1);
int result = n * recurse;
return result;
}
}
}
This is an exercise in the book I am stumped on. Why would the program not just recurse until the two numbers are equal and then return n ? Also, where it says,
int result = n * recurse;
How does it multiply int n by recurse which would be (int, int)? How can it multiply one integer by a set of two integers?
In what way am I misunderstanding this program?
EDIT: This is a different question because I am not using factorials
prod(x,y) is equivalent to y! when x=1.
If x is different from 1, then its doing recursive multiplication (y * (y- 1) * (y -2) .... ) until y = x.
Assuming y > x.
By the way, if x > y then prod() will crash.

Java: "Missing return statement"

I've having some trouble with recursion. At the moment, this code gives me an error message "missing return statement". Any way to get this working the way I want it to? I want it to calculate for xn and then return "count" when n reaches zero.
public class Question6p2 {
public static void main(String[] args){
int n = -6;
int x = 2;
int count = x;
power2(n, x, count);
System.out.println(power2(n, x, count));
}
public static int power2(int n, int x, int count){
if (n != 0){
if (n>0){
count = count * x;
n = n - 1;
}
else if (n<0) {
count = count * -x;
n = n + 1;
}
power2(n, x, count);
}
else if (n == 0){
return count;
}
}
}
Maybe I'm coming about this all wrong. Anyone care to help?
Currently, you have this statement:
power2(n, x, count);
... which ignores the result completely. In that branch, we never return anything from the method call. I suspect these two issues are linked.
I suspect you just want:
return power2(n, x, count);
Currently you are getting an error about not having a return statement because your return statement is within an if statement, so if that if statement doesn't run you will not return anything which is a problem.
Also I think you are going about recursion fundamentally wrong, as you are never calling back to your method recursively.
What you probably want to do within your power method is to accept n as the number of time to call your method, then lower it by 1 with each recursion. Then on every recursion multiply x by the original value.
Here is what I mean:
public static double power2(int n, int x,int xOriginal){
if(n == 0){
return 1;
}
if(n < 0){
return 1 / power2(n*-1, x, x);
}
if(n <= 1){
return x;
}
return power2(n -1, x * xOriginal, xOriginal);
}
Edit: Works with negative n now.
There are a few things wrong with your algorithm:
What does it mean to have a negative exponent?
You should understand that x-n can be written 1 / xn. This is not what was reflected in your algorithm.
All possible cases
There are 4 basic cases when calculating exponents.
There is any value x0 = 1.
Any x1 = x
Any negative exponent x-n = 1 / xn
Any positive exponent greater than one: xn where n > 1
Your algorithm should return 1 when x has an exponent of zero. Return x when the exponent is 1 or recursively call the algorithm when n > 1.
In the special case where n < 0 (ie you have a negative exponent) You can simply return the reciprocal 1 / method() as long as you change the sign of n before calling the method.
The line:
else if (n < 0){
n = -n;
return(1 / power2(n, x, count));
}
Checks for negative exponents, and returns 1 / xn Take note that the sign of n changed here, and now this is operating like any other method call with positive exponents.
public class TestCode {
public static void main(String[] args){
int n = 4;
int x = 5;
double count = x;
System.out.println(power2(n, x, count));
}
public static double power2(int n, int x, double count){
if (n == 0)
return 1;
else{
if (n > 1){
count = count * x;
n = n - 1;
}
else if (n < 0){
n = -n;
return(1 / power2(n, x, count));
}
else if (n == 1) {
return count;
}
return power2(n, x, count);
}
}
}

How do I return these using only one method?

public class newClass {
public static void main(String[] args)
{
int nullValue=0;
int nullValue2=1;
int nullValue3=0;
int nullValue4=0;
int [] sourceArray = {4,5,6,7};
int [] targetArray = new int [4];
for (int i=0; i<sourceArray.length; i++)
{
nullValue+=sourceArray[i];
}
targetArray[0]=nullValue;
// I added all sourceArray elements together and passed it to targetArray[0]
for (int i=0; i<sourceArray.length; i++)
{
nullValue2*=sourceArray[i];
}
targetArray[1]=nullValue2;
// I multiplied all sourceArray elements together and assigned the result to targetArray[1]
for (int i=0; i<sourceArray.length; i++)
{
nullValue3 += getResult(sourceArray[i]);
}
targetArray[2]=nullValue3;
// I tried to add all odd numbers in sourceArray together and assign it to targetArray[2]
for (int i=0; i<sourceArray.length; i++)
{
nullValue4 += getResult(sourceArray[i]);
}
targetArray[3]=nullValue4;
// Same as previous except I need to do that with even numbers.
}
public static int getResult (int x)
{
if (x%2 == 0)
{
return x;
}
else
{
return 0;
}
}
}
You can read my comments above. I realize I can create another method for the last part but I am supposed to use only one method to return odds and evens. I tried almost anything. I can't think of any other ways anymore. Obviously I can't return x in both cases(Yeah I was too desperate to try that).
Straight to the point. I need one method to return x if it's odd or if it's even(We can say it's impossible by the look of that sentence already). I guess that's impossible to do with only one method. I'm not good at java yet so I'm not sure. Maybe there are other ways to do that with only one method which may be so easy. I worked on it for like 6 hours so I'm asking you guys. Thanks.
Create a method to return a boolean if the number is even like so
public static boolean isEven(int x)
{
return (x%2 == 0)
}
Then in your loop for evens
for (int i=0; i<sourceArray.length; i++)
{
if(isEven(x))
nullValue3 += sourceArray[i];
}
For odds just change to if(!isEven(x))
But this is probably deviating from the requirements as you probably want a method that returns an int and you could just put the condition directly in the loop and not need a method
If I understand your question correctly, what you want is to be able to tell the getResult function whether to give you only odd numbers or only even numbers. Without getting complicated, this is what I would do:
public static int getResult(int x, boolean evens) {
if (x % 2 == 0) {
return evens ? x : 0; // shorthand for: if(evens) {return x;} else {return 0;}
} else {
return evens ? 0 : x;
}
}
Simply speaking, I pass a flag value (evens) to the getResult function. This flag tells me whether to filter for even numbers or for odd numbers.
I test whether x is even (x % 2 == 0). If it is, I return it if I'm looking for evens, and I return 0 if I'm looking for odds. If x wasn't even, then I do the opposite.
It would be a little cleaner to write a pair of helper functions, which you could then call from your getResult function.
private static int getIfEven(x) {
if (x % 2 == 0) {
return x;
}
return 0;
}
private static int getIfOdd(x) {
if (x % 2 == 0) {
return 0;
}
return x;
}
public static int getResult(int x, boolean evens) {
// shorthand for:
// if (evens) {
// return getIfEven(x);
// } else {
// return getIfOdd(x);
// }
return evens ? getIfEven(x) : getIfOdd(x);
}
Depending on how much you're allowed to deviate from the current setup (I assume this is homework), you could also just write an isEven(int x) function and call that at each step through the loop, only adding the number if it is/isn't even.

Categories

Resources