title: Creating a java program to convert decimal to binary?
body: <p>I'm working on a program that will display three choices. The three are:</p>
  
  <ul>
  <li>Converting decimal to binary</li>
  <li>Convert binary to decimal </li>
  <li>Exit.</li>
  </ul>
  
  <p>If the user writes "Exit" in the choice, the system to take the number and say "Goodbye". </p>
  
  <p>As of right now this is what I have. </p>
  
  <pre><code>import java.util.Scanner;
  
  public class binary {
  
      public String toBinary(int n) {
          if (n == 0) {
              return "0";
          }
          String binary = "";
          while (n &gt; 0) {
              int rem = n % 2;
              binary = rem + binary;
              n = n / 2;
          }
          return binary;
      }
  
      public static int binaryTodecimal(int i) {
          int n = 0;
          for (int pow = 1; i &gt; 0; pow *= 2, i /= 10)
              n += pow * (i % 10);
          return n;
      }
  
      public static void main(String[] args) {
  
          int answer2 = 0;
          String answer;
  
          final int info = 10;
          for (int i = 0; i &lt; info; i++) {
  
              Scanner kb = new Scanner(System.in);
              System.out.println("==================================");
              System.out.print("Enter your choice: ");
              answer = kb.next();
  
              if (answer.equalsIgnoreCase("3"))
                  System.exit(0);
  
              System.out.print("Enter a number: ");
              answer2 = kb.nextInt();
  
              binary decimalToBinary = new binary();
              String binary = decimalToBinary.toBinary(answer2);
  
              if (answer.equals("1"))
                  System.out.println("The 8-bit binary representation is: " + binary);
  
              binary bd = new binary();
              int n = bd.binaryTodecimal(answer2);
  
              if (answer.equals("2"))
                  System.out.println("The decimal representation is: " + answer2);
  </code></pre>
  
  <p>The questions I'm having is this. </p>
  
  <ol>
  <li><p>In trying to convert the number in answers2 to binary or decimal, I cannot figure out how to actually split the answer2 up for this to work. I thought of doing a loop, but not sure what else I can do. Could you by chance tell me what I need to do? I'm new in Java, still trying to learn the ropes. </p></li>
  <li><p>In converting decimal to binary, its printing out 6-bit or another bit, I want it specifically to be 8-bit. How can I fix this? Example:</p>
  
  
  
  <pre><code>Enter your choice: 1
  Enter a number: 16
  The 8-bit binary representation is: 10000
  </code></pre></li>
  </ol>