0

So my program is meant to take user input which is supposed to be a number from 1-511. Once the number is entered my program uses Integer.toBinaryString(); to turn their number into the binary form of that number. Then, if the binary output is not 9 digits, I want to fill the rest of that binary number with 0's until its 9 digits long. So I use an if statement to check if the length of the binary is less than 9, if it is I have it set to subtract 9 from binary.length so we can know how many zeros we need to add. Im currently stuck so I just made a print statement to see if its working so far and it does. But im not sure what to do as far as finishing it.

import java.util.Scanner;
public class Problem8_11 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

    System.out.print("Enter one number between 0 and 511: ");
    int number = input.nextInt();
    int binaryZeros = 9;

    String binary = Integer.toBinaryString(number);

    if(binary.length() < 9) {
        int amountOfZeros = 9 - binary.length();
        System.out.print(amountOfZeros);
  }

}

My question: How do I add the zeros to binary?

tcann99
  • 3
  • 3

1 Answers1

0

Presumably you want to prepend the zeros. There are many ways to do this. One way:

StringBuffer sb = new StringBuffer( Integer.toBinaryString(number) );
for ( int i=sb.length(); i < 9; i++ ) {
   sb.insert( 0, '0' );
}
String answer = sb.toString();

Be sure to handle the case where the number cannot be parsed into an integer.

FredK
  • 4,094
  • 1
  • 9
  • 11