Calculator Tester

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

10.0*nextDouble()

If you need a range with a minimum other than zero, add that minumum to the expression. For example, to get pseudorandom values in the range 10.0 up to (but not including) 25.9, do this

(25.9-10.0)*nextDouble()+10.0

Calculator Tester

Say that you are not convinced that Java and your electronic calculator give the same results for sin(x). You could test this by checking the values each produces for some standard angles, such as 0.0, pi/2 and so on. But you should also test several randomly selected angles. Here is a program that calculates sin(x) for random angles (in radians) between -10*pi and +10*pi.

import java.util.Random;

class SineTester
{
  public static void main ( String[] args )
  {
    int j=0;
    Random rand = new Random();
    
    System.out.println(" x " + "/t/t/t sin(x)");
    while (  j<10 )
    {
      double x = rand.nextDouble()*(20*Math.PI) - 10*Math.PI;
      System.out.println("" + x + "/t" + Math.sin(x));
      j = j+1;
    }
  }
}

Random values are often used for testing. Sometimes things work perfectly for standard values, but not for random ones. For example, some gas stations in California adjusted their pumps to dispense exactly the correct amount of fuel for multiples a half gallon, but to dispense less fuel for all other amounts. The Bureau of Weights and Measures tested the pumps at standard volumes (half a gallon, one gallon, ten gallons and such) so the pumps passed inspection. Testing random volumes would have revealed the scam.

QUESTION 12:

Might you ever need to simulate flipping a coin?