xcomsw
xcomsw

Reputation: 165

Java - Recursion with String returning with 0

I want to return the string "electric" with the number the user inputs. I have created the program. The problem is that it's returning with 0 rather than showing the output only. I know what the problem is, I just don't know the right solution.

Example :

Input : 3

Output :

Electric
Electric
Electric
0 <- should not have zero here.

import java.io.*;

public class quitx{
    public static BufferedReader v = new BufferedReader(new InputStreamReader(System.in));
    public static int s;
    public static void main(String[] args) throws Exception{
        System.out.println("Enter an integer  : ");
        s = Integer.parseInt(v.readLine());

            System.out.println(x(s));



    }

    public static int x(int s){
        if(s <= 0)
            return s;
        else{
            System.out.println("Electric!");
            return x (s - 1);
        }

    }
}

Upvotes: 0

Views: 55

Answers (3)

Eran
Eran

Reputation: 393791

Your method would always return 0, so instead of printing x(s), just call x(s) and then print s (not sure if you actually wanted to print that at the end)

Upvotes: 1

Smutje
Smutje

Reputation: 18123

Remove the return type of the method:

public static void x(int s){
    if (s > 0) {
        System.out.println("Electric!");
        x(s - 1);
    }
}

And change the call to

x(s);

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691705

The x() method returns an int. You don't want this int to be printed. Yet you're calling

System.out.println(x(s));

If you don't want the result to be printed, then... don't print it:

x(s);

Upvotes: 2

Related Questions