Domanda

/* This program converts decimal to binary */

import javax.swing.JOptionPane;

public class BinaryLoop {
public static void main(String []args) {

    String askForDecimal = JOptionPane.showInputDialog("Enter the decimal number you would like to convert?");
    int decimalNumber = Integer.parseInt(askForDecimal);

    int remainder = 0;
    for (int i = 1; decimalNumber > 0; i++) {

            decimalNumber /= 2;
            remainder = decimalNumber % 2;
            System.out.print(remainder);
        }

    }
}

For example I type in 15 but it returns 1110 which should be 1111. p.s. this the result will be read from right to left.

È stato utile?

Soluzione

decimalNumber /= 2;
remainder = decimalNumber % 2;

These two lines should be in the opposite order. Can you see why?

Altri suggerimenti

You don't need the variable i in your for loop at all, just use a while loop.

There is a flaw in your algorithm because you are dividing first:

15 / 2 = 7
7 / 2 = 3
3 / 2 = 1
1 / 2 = 0

You need to check the remainder before dividing, not afterwards.

If you understand the intent of the program, you should see the problem if you output some of the intermediate workings:

int remainder = 0;
for (int i = 1; decimalNumber > 0; i++) {
        System.out.println("Entering for() block");
        System.out.println("decimalNumber=" + decimalNumber);
        decimalNumber /= 2;
        System.out.println("decimalNumber=" + decimalNumber);
        remainder = decimalNumber % 2;
        System.out.println(remainder);
    }
}

Examine the output of this and the error should become obvious, which is that because two statements are the wrong way around, you're missing the first, biggest, value of decimalNumber.

You might also notice that remainder is not used outside the block, so you don't need to declare it outside the block, and you don't need to initialise it to zero.

Likewise, you might notice that the value of i is never used, so you could change the for loop to:

 for(;decimalNumber > 0;)

... which is equivalent to:

 while(decimalNumber > 0)

Many people get into the habit of putting temporary println statements in their code to debug. However it's a bad habit. Instead, learn to use a debugger as soon as you can. With a debugger you can pause a program and step through it line by line, looking at the values of all the variables as they change.

You need to do this:

String s = ""; Integer remainder = 0; while(decimalNumber > 0) { remainder = decimalNumber % 2; decimalNumber /= 2; s = remainder.toString() + s; } System.out.println(s);

you have to change the code to

remainder = decimalNumber % 2;
decimalNumber /= 2;

You have to get the remainder before dividing the number by 2.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top