Binary Encoder Your binary encoder should prompt the user to enter an integer be
ID: 3638334 • Letter: B
Question
Binary EncoderYour binary encoder should prompt the user to enter an integer between 0 and 255 in decimal format. Then, the binary encoder should print out the binary equivalent of that value. You may assume that the user will enter an integer between 0 and 255. You may not use any methods in the Integer class. You may not use more than 4 if statements in your final solution. Hint: Solve this problem with several if statements first, and then use a loop to reduce the amount of code in your solution.
Explanation / Answer
import java.util.Scanner; public class DecimalToBinaryConverter { public static void main(String[] args) { Scanner in = new Scanner(System.in); int decimalNumber; String binaryNumber; boolean valid = false; do { System.out.print("Enter a number between 0 and 255: "); decimalNumber = in.nextInt(); if (decimalNumber < 0 || decimalNumber > 255) System.out.println("ERROR: number must be between 0 and 255."); else { valid = true; } } while(!valid); binaryNumber = ""; if (decimalNumber ==0) { binaryNumber = "0"; } else { while (decimalNumber != 0) { binaryNumber = (decimalNumber % 2) + binaryNumber; decimalNumber /= 2; } } System.out.println("Binary: " + binaryNumber); } }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.