← Java from Scratch Lesson 38 of 88 · 10 XP

Packages and the API

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A package is a folder for classes: java.util, java.time, java.io. The full name of a class is java.util.Scanner. import lets you write the short name:

import java.util.Scanner;     // one class
import java.util.*;           // all the classes of a package (not its subpackages)
import static java.lang.Math.*;   // static members: sqrt(2) instead of Math.sqrt(2)

java.lang (String, Math, System, Integer) is always imported.

Your own package is declared on the first line of a file: package com.igd.game; — and the file lives in the folder com/igd/game/. Package names are a domain written backwards, so they don't clash with other people's.

The Java API is thousands of ready-made classes: collections, dates, files, networking, threads. The documentation is at docs.oracle.com.

Task. Use java.util.Random with a seed from the input — then the "random" numbers repeat the same way on any machine, which is handy for tests and for replays in games. Read seed and n, "roll a die" n times (rnd.nextInt(6) + 1), print the rolls separated by spaces and, on the second line, their sum.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.