Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)
edited by

Below is my code which converts decimal to binary from the user's input in Java:

package reversedBinary;

import java.util.Scanner;

public class ReversedBinary {

public static void main(String[] args) {

    int number; 

    Scanner in = new Scanner(System.in);

    System.out.println("Enter a positive integer");

    number=in.nextInt();

    if (number <0)

        System.out.println("Error: Not a positive integer");

    else { 

        System.out.print("Convert to binary is:");

        System.out.print(binaryform(number));

}

}

private static Object binaryform(int number) {

    int remainder;

    if (number <=1) {

        System.out.print(number);

    }

    remainder= number %2; 

    binaryform(number >>1);

    System.out.print(remainder);

    { 

    return null;

} } }

But I’m getting errors when I run the above code. Can anyone tell me how to convert decimal to binary?  

1 Answer

0 votes
by (19.7k points)
edited by

The method ‘binaryForm’ in your code is going on in an infinite recursion, to avoid it you need to return with the condition number <= 1:

Check the code below:

import java.util.Scanner;

public class ReversedBinary {

    public static void main(String[] args) {

        int number;

        Scanner in = new Scanner(System.in);

        System.out.println("Enter a positive integer");

        number = in.nextInt();

        if (number < 0) {

            System.out.println("Error: Not a positive integer");

        } else {

            System.out.print("Convert to binary is:");

            //System.out.print(binaryform(number));

            printBinaryform(number);

        }

    }

    private static void printBinaryform(int number) {

        int remainder;

        if (number <= 1) {

            System.out.print(number);

            return; // KICK OUT OF THE RECURSION

        }

        remainder = number % 2;

        printBinaryform(number >> 1);

        System.out.print(remainder);

    }

}

Interested in Java? Check out this Java Certification by Intellipaat.   

Related questions

0 votes
0 answers
0 votes
1 answer
0 votes
1 answer
asked Mar 14, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...