Lesson 2 of 10

Types and casting

Goal

Integer division, long and Math.round

01

Explanation

In Java you set each variable's type when you declare it, and that type never changes: int for whole numbers, double for decimals, boolean for true or false, char for a single character written between single quotes like 'A', and String for text written between double quotes. The largest value an int can hold is about 2.1 billion, so when you need more, use long and put the letter L after the number: 3_000_000_000L.

The first trap is that dividing an integer by an integer gives an integer and drops the fraction, so 47 / 6 is 7. Storing the result in a double doesn't bring the fraction back, because it was already lost, so cast one side before dividing: (double) kills / deaths. The same trap shows up in multiplication: players * xpEach is computed as an int, so it overflows and turns negative before it ever reaches the long. Write (long) players * xpEach instead.

(int) 30.83 drops the fraction and gives 30, while Math.round(30.83) rounds to 31. But Math.round returns a long, and Java won't turn it into an int on its own, so write (int) Math.round(x). To round to two decimal places, write Math.round(x * 100) / 100.0, and don't drop the .0, or the division becomes integer division again.

02

Your task

Run the code and look at the two numbers, then fix the three methods. Make kdRatio(kills, deaths) return the ratio as a decimal rounded to two places, so 47 and 6 give 7.83. Make totalXp(players, xpEach) return the total without overflowing, and make healthPercent(hp, maxHp) return the percentage rounded to the nearest whole number, so 37 out of 120 gives 31, not 30.

Checks

5 checks
  1. kdRatio(47, 6) returns 7.83
  2. kdRatio doesn't drop the fraction
  3. totalXp reaches three billion without overflowing
  4. healthPercent rounds instead of truncating, so 37 out of 120 gives 31
  5. The K/D of 7.83 and the total XP of 3000000000 were printed
03

Hints

0/3
Track lessons0 of 10 done

Java is the language behind Android apps and large systems. Everything in it lives inside a class, and you state every variable's type explicitly.

Beginner level, 10 lessons, 2 hours in total.

Main.java
OutputJava 13 (Judge0)

Compiling and running your code on the server.

–/5

Compiling and running your code on the server.

5 checks listed under “Your task”.

Track lessons0 of 10 done

Java is the language behind Android apps and large systems. Everything in it lives inside a class, and you state every variable's type explicitly.

Beginner level, 10 lessons, 2 hours in total.