Programming
Display both the original integer and the binary output

Question 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.

Student has agreed that all tutoring, explanations, and answers provided by the tutor will be used to help in the learning process and in accordance with Studypool's honor code & terms of service.

Final 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




University of Virginia

Anonymous
Super useful! Studypool never disappoints.

Studypool
4.7
Trustpilot
4.5
Sitejabber
4.4