Ok, this must be something really stupid....my statement is returning 2:
When I print out the values they are all correct
The return statement is wrong somehow
Code:
public static void main (String [] args)
{
System.out.println(countToTen(1));
}
public static int countToTen(int last_answer){
last_answer++;
if(last_answer != 10){
countToTen(last_answer);
}
return last_answer;
}
Try replacing your if statement with:
if(last_answer != 10){
return countToTen(last_answer);
}
Without the return statement, the recursive calls do get executed, but the calculated result is never returned.
The order of calls with your broken code looks like:
countToTen(1)
-> countToTen(2)
--> countToTen(3)
---> more calls to countToTen()
--- ... --> countToTen(10) // do nothing, and return to the top-level method call
-> return 2 // 2 because you incremented it using lastAnswer++
Your function returns the value from the first call. It is the initial value (1) incremented once by the ++ statement, so the function returns 2.
Integers are passed by value in Java, incrementing the passed value inside the function does not change the value outside:
int x = 0;
v(x);
// x still 0 here.
void v(int x) {
x = 100;
}
Try this:
public static int countToTen(int last_answer){
last_answer++;
if(last_answer != 10){
return countToTen(last_answer);
}
else {
return last_answer;
}
}
If you want to print out 1,2,3,4 ... 10, you need to print out the answer in every phase separately
public static void main (String [] args){
countToTen(1);
}
public static void countToTen(int last_answer){
System.out.println(last_answer);
last_answer++;
if(last_answer <= 10){
countToTen(last_answer);
}
}
My proposal
public static int countToTen(int last_answer){
last_answer++;
if(last_answer < 10){
return countToTen(last_answer);
} else {
return last_answer;
}
}
You are not passing the argument by reference, it is a copy. You are doing a modification in last_answer in the context of method, but this change is not propagate outside, because in the end you return last_answer++
public static void main (String [] args)
{
System.out.println(countToTen(1));
}
public static int countToTen(int last_answer)
{
last_answer++;
if(last_answer != 10)
{
return countToTen(last_answer); //Here was the error
}
return last_answer;
}
Related
I'm using recursion to print numbers until 2(number), and I'm passing zero(0) as input and recursively calling it until the number reaches 2.
I have tried this code, and it shows the correct output.
class Test{
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num<=2){
rec(++num);
}
System.out.println(num);
}
}
but I want to do this with the following way.
class Test{
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num==2){
return;
}
rec(++num);
System.out.println(num);
}
}
Expected output:
2,1,0
but it shows:
2,1
Why does it happen?
++num increments num, which (as here) makes the code harder to understand.
Try calling rec(num + 1); instead.
You may find your terminating condition needs to be modified to:
if (num > 2)
Terminating conditions are usually the “do nothing” case, which is the case here.
When you are calling rec(++num);, you are incrementing num before printing it out. So when you use 0 as input, by the time it prints num will have changed to 1. When num = 2 at the start of rec(), the print does not execute.
rec(0) prints rec(1),1
rec(1) prints rec(2),2
rec(2) prints nothing
Total output: 2,1
It happens because ++num doesn't just return num + 1 it also modifies num like num = num + 1.
Your if statement is also backwards.
public class Test {
public static void main(String[] args) {
rec(0);
}
private static void rec(int num) {
if (num < 2) {
rec(num + 1);
}
System.out.println(num);
}
class Test {
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num <= 2){
rec(num + 1);
} else return;
System.out.println(num);
}
}
++num - prefixes increment, it means that it's incremented before System.out.println(num); was called. So, first, you check the case of recursion call. If it condition is false - get out of recursion. And when printing value.
When you are working with recursion, try to spread out nested blocks of code, when you will understand simpler.
I have a problem with my Java Code at the fourth line.
I have this error: "this method must return a result of type int".
So I didn't return 'c'. How can I return?
public class bese_bolunme {
static int function(int b)
{
for (int c=0;c<b;c++)
{
if(c%5==0)
{
System.out.println(c);
return c;
}
}
}
public static void main(String[] args) {
function(36);
}
Since you declared in your function signature that it returns an Integer, you must, in all execution flows of your function return an Integer.
static int function(int b)
{
for (int c=0;c<b;c++)
{
if(c%5==0)
{
System.out.println(c);
return c;
}
} //end for loop
return -1; //Or other logic you prefer
}
On every execution path in the method function(int b) a return statement must be reached. You are taking care of not all paths: I.e. what should the method return in case of not entering the for loop?
Please help as how can I achieve below in java.
public class TestUserFunctions {
public static boolean equals(int val1, int val2){
if(val1==val2){
return true;
} else{
return false;
}
}
public static Object iterateValue(String ittr, int iterations){
for(int i=1; i <= iterations; i++){
System.out.println("Printing iteration #"+i);
}
return ittr;
}
private static void ifElse(boolean condition, Object returnstr, Object elsestr){
if(condition){
System.out.println("TRUE");
//Need a code here which will iterate string value only once.
} else{
System.out.println("FALSE");
//Need a code here which will iterate string value thrice as specified.
}
}
public static void main(String[] args){
ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3));
}
}
I may be wrong in many aspect here with my above code. I am sorry for that.
The expected output here is
TRUE
Printing iteration #1
In case of ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3)); the expected output is
FALSE
Printing iteration #1
Printing iteration #2
Printing iteration #3
The point is:
ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3));
In Java, all method arguments get evaluated (aka computed) before the invocation takes place.
In other words:
equals(1,1) will always result in true
thus always the first "Value" is returned (although that doesn't really matter; as you are using the same value in both cases)
as said, both calls to iterateValue() will be executed; that means that this method is invoked twice, with the respective arguments for each call.
So, if you want to call iterateValue() only once; you should not use it as parameter. Instead, go for something like:
ifElse(equals(1,1), "ValueA", "ValueB"));
and then call iterateValue() on the first or second incoming String argument directly; and only once.
You need to defer execution of the if and else block using Java 8 lambda expressions to obtain what you want to achieve
import java.util.function.Supplier;
public class TestUserFunctions {
public static Supplier<Boolean> equals(int val1, int val2){
if(val1==val2){
return () -> true;
} else{
return () -> false;
}
}
public static Supplier<String> iterateValue(String ittr, int iterations){
return () -> {
for(int i=1; i <= iterations; i++){
System.out.println("Printing iteration #"+i);
}
return ittr;
};
}
private static void ifElse(Supplier<Boolean> condition, Supplier<String> returnstr, Supplier<String> elsestr){
if(condition.get()){
System.out.println("TRUE");
returnstr.get();
} else{
System.out.println("FALSE");
elsestr.get();
}
}
public static void main(String[] args){
ifElse(equals(1, 1), iterateValue("Value", 1), iterateValue("Value", 3));
}
}
Using Java < 8 the readability is greatly decreased
interface Supplier<T> {
public T get();
}
public class TestUserFunctions {
public static Supplier<Boolean> equals(int val1, int val2){
if(val1==val2){
return new Supplier<Boolean>() {
public Boolean get() { return true; }
};
} else{
return new Supplier<Boolean>() {
public Boolean get() { return false; }
};
}
}
public static Supplier<String> iterateValue(String ittr, int iterations){
return new Supplier<String>() {
public String get() {
for(int i=1; i <= iterations; i++){
System.out.println("Printing iteration #"+i);
}
return ittr;
};
};
}
private static void ifElse(Supplier<Boolean> condition, Supplier<String> returnstr, Supplier<String> elsestr){
if(condition.get()){
System.out.println("TRUE");
returnstr.get();
} else{
System.out.println("FALSE");
elsestr.get();
}
}
public static void main(String[] args){
ifElse(equals(1, 2), iterateValue("Value", 1), iterateValue("Value", 3));
}
}
Your problem can be expressed more succinctly like this:
public class Demo() {
static int x = 0;
static int incrementAndReturnX() {
x++;
return x;
}
static void ifElse(boolean predicate, int t, int f) {
if(predicate) {
return t;
} else {
return f;
}
}
static void main(String... args) {
System.out.println(ifElse(false, incrementAndReturnX(), incrementAndReturnX());
}
}
This prints 2.. Why is this, and how can we make it return 1?
The answer is the order in which Java calls methods. When it deals with ifElse(true, incrementAndReturnX(), incrementAndReturnX()), it runs the methods passed as parameters, so as to get an object or a primitive. Then it invokes ifElse().
So:
Java notes that true is a primitive. Nothing to do. Move on.
Java calls incrementAndReturnX(). x is incremented. 1 is returned.
Java calls incrementAndReturnX() again. x is incremented. 2 is returned.
Java uses the values it has collected to call ifElse(false, 1, 2)
You can see that the result of this is 2.
What we need is some way of passing a method to the ifElse() routine, as if it was an object, so that it can choose whether to run it or not. In Java 7, the only way we could do that was by creating classes containing our methods, so we could pass them around.
interface IntegerSupplier() {
int get();
}
...
final int[] x = new int[1];
IntegerSupplier incrementAndReturnX = new IntegerSupplier() {
x[0] += 1;
return x[0];
};
Note this is using anonymous class syntax. We are creating a new class here, and creating an instance of it, without giving it a name.
We are also wrapping x in an array, because the inner class can only refer to final variables, and we need to be able to modify the value.
public int ifOrElse(boolean predicate, IntegerSupplier t, IntegerSupplier f) {
if(true) {
return t.get();
} else {
return f.get();
}
}
The key here is that the code that increments x is in a method that's not called until inside the if block.
As of Java 8, we have a much neater way of doing the same thing. We can very succinctly declare something very like our IntegerSupplier using what is called a lambda:
Supplier<Integer> incrementAndReturnX = () {
x[0]++;
return x;
}
public int ifOrElse(boolean predicate, Supplier<Integer> t, Supplier<Integer> f) {
if(true) {
return t.get();
} else {
return f.get();
}
}
(java.util.function.Supplier is provided by the JRE: we don't need to declare our own)
This whole way of thinking is called functional programming, and is very powerful and expressive.
what is the reason that i am getting java.lang.stackoverflowerror after running this code?
class recursion {
public static int func(int n) {
int result;
result = func (n - 1);
return result;
}
}
class Output {
public static void main(String args[]) {
recursion obj = new recursion();
System.out.print(obj.func(12));
}
}
You have no stopping condition.
You always call func (n - 1), and therefore get an infinite chain of recursive calls until the stack overflows.
A proper recursive method must have a stopping condition. For example, the stopping condition may be when n reaches 0 :
public static int func (int n) {
if (n <= 0)
return 1;
int result = func (n - 1);
return result;
}
When is the method func stopping?
You are calling it with 12 and then is going back to an infinite recursion.
On an unrelated note: you should take a look at the Java code conventions
This is because there is no limit (end point) for the recursive function call.
Try this -
class recursion
{
public static int func (int n)
{
int result = 0;
if(n > 0)
result = func (n - 1);
return result;
}
}
class Output
{
public static void main(String args[])
{
System.out.print(recursion.func(12));
}
}
You should call static function with class name.
Why does this code give me an error? I'm tyring to return the index of the first string in strArr that matches string s.
private String strArr[];
public int indexOf(String s) {
for(int i=0;i<strArr.length ;++i) {
if (strArr[i].equals(s)){
return i;
}
}
}
You are not initialising the array (therefore will get a NullPointerException when you try and get it's length)
You are not returning from the method if the string is not found
public class StringArrayIndex {
private String strArr[] = new String[]{"bar","foo", "cas"};
public int indexOf(String s) {
for(int i=0;i<strArr.length ;++i) {
if (strArr[i].equals(s)){
return i;
}
}
return -1;
}
public static void main(String[] args){
System.out.println(new StringArrayIndex().indexOf("foo"));
}
}
When submitting to Stack Overflow you should try to give more information (full code samples, error messages etc) so people can help you more easily.
You need to also return some value e.g. -1 after your loop.
Your return is in an IF statement so the Java compiler is
not sure you will ever enter this IF. And if you don't, you might
never return a value from your method. Therefore the compile-tome error.
You are not returning anything if you do not find the string in the array.
You should return something if the condition is never evaluated to true (outside your for loop for instance, you could return -1).
In your case, not all paths return a value.
because if your method need to return something, it should return in all cases:
public int indexOf(String s) {
for(int i=0;i<strArr.length ;++i) {
if (strArr[i].equals(s)){
return i;
}
}
return -1; //if not find
}
it should return if your condition never get satisfied.
public class MyIndexOf {
private String strArr[] = {"x", "y", "z"};
public int indexOf(String s) {
for (int i = 0; i < strArr.length; i++) {
if (strArr[i].equals(s)){
return i;
}
}
return -1;
}
public static void main(String[] args) {
MyIndexOf self = new MyIndexOf();
System.out.println(self.indexOf("x"));
}
}