Decimal to Binary converter loop

I’m supposed to create a program that takes user-entered decimal number and converts it to binary using an inner and outer for or while loop.

For some reason, whenever I enter a positive integer the program just does nothing.

My code:

public class Dec2Bin
{
    public static void main (String[] args)
    {
        System.out.println("Welcome to Decimal Number to Binary Converter");
        System.out.println("");

        Scanner s = new Scanner(System.in);
        while (true)
        {
            String binary = "";
            System.out.print("Enter a decimal number (-1 to end)");
            int input = s.nextInt();

            if (input <= 0)
            {
                System.out.println("Goodbye!");
                break;
            }

            int result = input;

            while (result >= 0)
            {
                result = result / 2;
                binary = (result % 2) + binary;
            }
            System.out.println("Binary number is " + binary);
        }
    }
}

It should be prepending the remainder from result%2 to the binary string each time and that string should show the converted binary number. It does work as it’s supposed to if I enter a negative number, displaying the “Goodbye!” message. Not sure where I went wrong.


Download decimal.to.binary.converter.loop.zip
Direct Link


Download


Download decimal.to.binary.converter.loop.zip
Mediafire


Download


Download decimal.to.binary.converter.loop.zip
KeepFile


Download


Download decimal.to.binary.converter.loop.zip
Bitshare


Download


Download decimal.to.binary.converter.loop.zip
Filedropper


Download

Both comments and pings are currently closed.

Comments are closed.