Pages

Sunday, 3 July 2016

Chapter 4 Exercise 12, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

4.12 (Hex to binary) Write a program that prompts the user to enter a hex digit and displays its corresponding binary number. Here is a sample run:

Enter a hex digit: B
The binary value is 1011
Enter a hex digit: G
G is an invalid input 




import java.util.Scanner;
 
public class ProgrammingEx4_12 {
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.print("Enter a hex digit: ");
  String hexString = input.nextLine();
 
  // Check if the hex string has exactly one character
  if (hexString.length() != 1) {
   System.out.println("You must enter exactly one character");
   System.exit(1);
  }
 
  // Display decimal value for the hex digit
  char ch = Character.toUpperCase(hexString.charAt(0));
  int value = 0;
  if (ch <= 'F' && ch >= 'A') {
   value = ch - 'A' + 10;
  } else if (Character.isDigit(ch)) {
   value = ch - '0';
  } else {
   System.out.println(ch + " is an invalid input");
   System.exit(0);
  }
 
  System.out.println("The decimal value for hex digit " + ch + " is "
    + Integer.toBinaryString(value));
 
 }
}

No comments:

Post a Comment