Display both the original integer and the binary output

User Generated

Whyrfc

Programming

Description

- Prompt the user for a positive integer less than 100.
- Convert the integer into its binary representation, you MUST hard code the solution with your own algorithm with loop NOT using the java buit-in method such as: Integer.toBinaryString(int ).
- Display both the original integer and the binary output.

User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.

Explanation & Answer

Here's the Java program that works.  For a dollar you don't get much error checking or formatting.  Please contact me if you need any additional help.  Depending on what you want it could be free or cost a little $$.


import java.util.Scanner;

public class Integer2Binary {

  private static Scanner kb = new Scanner(System.in);

  public static void main(String[] args) {
  System.out.println(
  "\nProgram to get postive integer < 100 and convert to binary\n");
  int n;
  do {
  System.out.print("Enter an integer (0<n<100): ");
  n = kb.nextInt();
  } while (!(0 < n && n < 100));
  int nSav = n;
  // convert the int to binary:
  String binStr = "";
   
// since n<100, the largest power of 2 that fits will be 64 = 2^6
  binStr += n / 64;
  n = n % 64;
  binStr += n / 32;
  n = n % 32;
  binStr += n / 16;
  n = n % 16;
  binStr += n / 8;
  n = n % 8;
  binStr += n / 4;
  n = n % 4;
  binStr += n / 2;
  n = n % 2;
  binStr += n;
  // convert string to numbers:
  int binNum = Integer.parseInt(binStr);
  System.out.println(""
  + "\nThe original decimal integer: " + nSav
  + "\nThis number's binary equivalent is: " + binNum);
  }
}
Integer2Binary.java




Related Tags