FileDocCategorySizeDatePackage
RandomNos.javaAPI DocExample1724Fri Aug 11 13:39:18 BST 2000None

RandomNos.java

import java.awt.*;		// make the graphics libraries available
import java.applet.*;	// make the applet libraries available
import java.util.*;		// make the random number library available
								// The random number generator returns a value
								// in the range 0.00 - 0.999. We need to convert this
								// into an integer value in the range 1 - 100

//Create an applet, generate and display 10 random numbers and calculate
//the average of these numbers.

public class RandomNos extends Applet // make a new applet
{
	private int randomNumber;		// to hold the value of a random number
	private int textXPosition ;	// position of text
	private int textYPosition ;
	private double sum ;				// variable to hold sum of random numbers
	private double average ;		// average of 10 random numbers
		
	public void paint(Graphics g)
	{
		textXPosition = 0 ;  // initialise position of text
		textYPosition = 50 ;
		sum = 0.0 ;				// initialise sum to zero
		
		// define an int, count, and initialise it to one. Repeat the for
		// loop until count = 10, and increment count by one each time
		// round the loop.
		for (int count = 1 ; count <= 10 ; count++)
		{
			// get a value for the random number
			randomNumber  = (int) (Math.random() * 100) + 1; 
		
			// add the random number to sum
			sum = sum + randomNumber ;
			
			// write the random number
			g.setColor(Color.blue);
			g.drawString("" + randomNumber, textXPosition, textYPosition);
									
			// increment postion coordinates
			textXPosition = textXPosition + 30 ;
		}
		
		// calculate average
		average = sum / 10 ;
		
		g.drawString("The average of these numbers is: " + average, 0, 100) ;							
	}
}