Random box

This applet uses the random method to generate a random number. Math.random is part of the java.lang package and is imported by default. The random method returns a random double between 0.0 and 0.9999…
Multiplying and turning the result into an integer produces random numbers in the desired range.

import java.awt.*;
import java.applet.Applet;

public class RandomBox extends Applet {

public void paint(Graphics g)

int size;
//Generate a random integer between 30 and 50 for the box size
size = (int) (Math.random () * 31) + 20;
g.drawString("A random box between 20 and 50 pixels ", 50, 20);
g.drawRect(50, 50, size, size);



The output is:

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License