*4.11 (Decimal to hex) Write a program that prompts the user to enter an integer between 0 and 15 and displays its corresponding hex number. Here are some sample runs:
Enter a decimal value (0 to 15): 11
The hex value is B
Enter a decimal value (0 to 15): 5
The hex value is 5
Enter a decimal value (0 to 15): 31
31 is an invalid input
Enter a decimal value (0 to 15): 11
The hex value is B
Enter a decimal value (0 to 15): 5
The hex value is 5
Enter a decimal value (0 to 15): 31
31 is an invalid input
import java.util.Scanner; public class ProgrammingEx4_11 { public static void main(String[] args) { System.out.print("Enter a decimal value (0 to 15): "); Scanner input = new Scanner(System.in); int i = input.nextInt(); if (i < 0 || i > 15) { System.out.println(i + " is an invalid input"); System.exit(0); } System.out.println("The hex value is " + Integer.toHexString(i).toUpperCase()); } }
No comments:
Post a Comment