THINK FIRST·CODE LATER

← All labs

The Ariane 5 conversion: detect overflow instead of hiding it

Problem

Ariane 5 was lost because a 64-bit floating-point value was converted to a 16-bit signed integer that could not hold it. In Java, a 16-bit signed integer is a short, with range −32768 … 32767. A plain cast like (short) 40000.0 does not fail — it silently produces a wrong value.

Write a program that reads n and then n real numbers (sensor values). For each value v:

  • if v is between −32768 and 32767 (inclusive), convert it by truncating toward zero (as (short) v would) and print v -> result;
  • otherwise print v -> OVERFLOW (a plain cast would give X), where X is the wrong value that (short) v actually produces.

Print v exactly as Java prints a double. At the end print Safe: a, Overflow: b.

For the input

4
123.9
40000
-32768
-40000.5

the output must be:

123.9 -> 123
40000.0 -> OVERFLOW (a plain cast would give -25536)
-32768.0 -> -32768
-40000.5 -> OVERFLOW (a plain cast would give 25536)
Safe: 2, Overflow: 2

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.

s1-1-data-1.txt

4
123.9
40000
-32768
-40000.5
What your program must print for s1-1-data-1.txt
123.9 -> 123
40000.0 -> OVERFLOW (a plain cast would give -25536)
-32768.0 -> -32768
-40000.5 -> OVERFLOW (a plain cast would give 25536)
Safe: 2, Overflow: 2

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 < s1-1-data-1.txt

Windows PowerShell does not understand <:

Get-Content s1-1-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.