THINK FIRST·CODE LATER

← All labs

Binary and hexadecimal: your own format exceptions

Problem

Write two unchecked exceptions, BinaryFormatException and HexFormatException, both extending NumberFormatException. Each receives the faulty text and the position of the bad character, and builds a message such as

"10201" is not binary: character '2' at position 2

Then write BaseConverter with the static methods binToDec(String) and hexToDec(String) (lower-case hex digits are accepted), which convert digit by digit and throw the matching exception at the first illegal character.

main reads pairs bin text or hex text until the end of the input; for any other first word it throws an IllegalArgumentException("Unknown base: …") itself. All errors are caught and counted. For the input

bin 1011
hex FF
bin 10201
hex 1G
oct 17
hex cafe
bin 0

the program prints

1011 in binary is 11
FF in hexadecimal is 255
Format error: "10201" is not binary: character '2' at position 2
Format error: "1G" is not hexadecimal: character 'G' at position 1
Unknown base: oct
cafe in hexadecimal is 51966
0 in binary is 0
4 converted, 3 error(s)

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l16-6-data-1.txt

bin 1011
hex FF
bin 10201
hex 1G
oct 17
hex cafe
bin 0
What your program must print for l16-6-data-1.txt
1011 in binary is 11
FF in hexadecimal is 255
Format error: "10201" is not binary: character '2' at position 2
Format error: "1G" is not hexadecimal: character 'G' at position 1
Unknown base: oct
cafe in hexadecimal is 51966
0 in binary is 0
4 converted, 3 error(s)

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l16-6-data-1.txt

Windows PowerShell does not understand <:

Get-Content l16-6-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.