0

the idea is that the program will show numbers and their binary equivalent but it is showing only the numbers and one binary on the end,what is wrong

public class Convert {

    public static void main(String[] args) {
        int number;
        for (number = 0; number < 4095; number++) {
            System.out.println("Number is :" + number);
        }
        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);
            return null;
        }
        remainder = number % 2;
        binaryform(number >> 1);
        System.out.print(remainder); {
        }
        return remainder;
    }
}
3
  • Why are you using your own binary calculation when there is a built in lib? Commented May 15, 2013 at 17:15
  • how to go there?in this lab. Commented May 15, 2013 at 17:34
  • @Dan4o He means the method suggested by user000001: Using the pre-defined method Integer.toBinaryString(number) instead of defining your own method binaryForm(number). Commented May 15, 2013 at 17:37

3 Answers 3

2

You can use

Integer.toBinaryString(number));
Sign up to request clarification or add additional context in comments.

Comments

1

change it as below

for(number=0;number<4095;number++){

System.out.println("Number is :"+ number);
System.out.print("Convert to binary is:");
System.out.print(binaryform(number));
}

5 Comments

because in the for loop you should do whatever you want for each number.at the end of the loop the number will be 4095 and it will exit the loop.so the binary was printed for you is for 4095
The code works but starts around 2500,not from 0,what is wrong now?And the binary is 13 numbers ,but they supposed to be 12...........
@Dan4o It does start at 0. However, it most likely shows the x most recent lines only, to save memory. Also, your binaryForm method is wrong.
@Dan4o it is because of memory leak or a lack of execution memory.You can write it to a file and checked or just increase the memory and test.If you change the number in the loop from 4095 to 200 then you will see that it is printing from 0
@Dan4o Integer.toBinaryString(number)) is ok
0

In here:

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

you are not in the for loop, so that it will only print out the numbers and just the last number's binary equivalent.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.