|
-
November 21st, 2015, 03:36 PM
#1
Add error message when user types values outside range & limit user input to 2 values
Dear community,
I just started learning java a few weeks ago and needing a hand.
- Need some help adding an error message when a user types in values out of range, in regard to the Hex user input where values have to be 0-9 and A to F.
- I would also like to limit the user's input to just 2 digits/letters.
The program I am constructing is one which converts a Hexadecimal value to its Binary and Decimal equivalents.
Below is the code.
import java.util.Scanner;
public class Converter_6_ColinKagame {
public static void main(String args[]) {
// User is requested to type a Hex value
System.out.println("Please enter a Hexadecimal number : ");
Scanner scanner = new Scanner(System.in);
//Two characters max can be input
//Is the value within valid range,
String hexadecimal = scanner.next();
//Conversion: Hex to decimal
int decimal = Integer.parseInt(hexadecimal, 16);
System.out.println("Decimal equivalent is: " + decimal);
//Conversion: Hex to binary
String binary = Integer.toBinaryString(decimal);
System.out.printf("Binary equivalent for %s is: %s %n", hexadecimal, binary );
}
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|