THINK FIRST·CODE LATER

← All labs

A light-year: choosing between int, long, double and float

Problem

Light travels 299 792 458 metres per second. Write LightYear with that value as an int constant SPEED_OF_LIGHT. Read a number of light-years (a double) and print:

  1. the seconds in a year (365 days) — an int;
  2. SPEED_OF_LIGHT * secondsPerYear computed as an int (wrong: overflow);
  3. the same product computed as a long (cast one operand first);
  4. the distance in km as a double, 5. the same value cast to float, and 6. the whole number of billions of km (cast to long).

For the input

1

the program prints

Seconds in a year: 31536000
int result (wrong): 1144840960
One light-year in metres: 9454254955488000
1.0 light-years in km: 9.454254955488E12
The same as a float: 9.454255E12
Whole billions of km: 9454

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.

l3-6-data-1.txt

1
What your program must print for l3-6-data-1.txt
Seconds in a year: 31536000
int result (wrong): 1144840960
One light-year in metres: 9454254955488000
1.0 light-years in km: 9.454254955488E12
The same as a float: 9.454255E12
Whole billions of km: 9454

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

Windows PowerShell does not understand <:

Get-Content l3-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.