38 Chapter 3: Using Classes and Objects
// *******************************************************************
// RightTriangle.java
public class RightTriangle
{
public static void main (String[] args)
Scanner scan = new Scanner(System.in);
————————————————————-;
————————————————————-;
// Compute the length of the hypotenuse
————————————————————-;
}
3. In many situations a program needs to generate a random number in a certain range. The Java Random class lets the
programmer create objects of type Random and use them to generate a stream of random numbers (one at a time). The
following declares the variable generator to be an object of type Random and instantiates it with the new operator.
The generator object can be used to generate either integer or floating point random numbers using either the nextInt
method (either with no parameter or with a single integer parameter) or nextFloat (or nextDouble) methods,
respectively. The integer returned by nextIn(t could be any valid integer (positive or negative) whereas the number
returned by nextInt(n) is a random integer in the range 0 to n-1. The numbers returned by nextFloat() or nextDouble()
are floating point numbers between 0 and 1 (up to but not including the 1). Most often the goal of a program is to
generate a random integer in some particular range, say 30 to 99 (inclusive). There are several ways to do this:
• Using nextInt(): This way we must use the % operator to reduce the range of values—for example,
will return numbers between 0 and 69 (because those are the only possible remainders when an integer is divided by
70 – note that the absolute value of the integer is first taken using the abs method from the Math class). In general,
using % N will give numbers in the range 0 to N -1. Next the numbers must be shifted to the desired range by
adding the appropriate number. So, the expression
Math.abs(generator.nextInt()) % 70 + 30
will generate numbers between 30 and 99.