Monday, November 3, 2014

Java generate random pro



Generate random numbers

public class GenerateRandomNumbers
{   
public static void main(String[] args)
{
System.out.println("Random numbers between 0.0 and 1.0 are,");
for(int i=0; i < 5 ; i++)
System.out.println("Random Number ["+ (i+1) + "] : " + Math.random());
System.out.println("Random numbers between 1 and 100 are,");
for(int i=0; i < 5 ; i++)
System.out.println("Random Number ["+ (i+1) + "] : " + (int)(Math.random()*100));
  }
}

Draw Dots at Random Locations in an Applet

import java.applet.Applet;
import java.awt.Dimension;
import java.awt.Graphics;
ublic class DrawDotsAtRandomLocationsExample extends Applet implements Runnable
{
 Thread t;
 public void init()
{
t = new Thread(this);
t.start();
}
public void run()
{
try
{
           while(true)
{
repaint();
Thread.sleep(200);
  }
}
catch(Exception e)
  {
   }
 }
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
      
Dimension d = getSize();
int x = (int)(Math.random() * d.width);
int y = (int)(Math.random() * d.height);
g.fillRect(x,y,2,2);
   }
}

Generate Random Int Within Given Range

public class GenerateRandomIntByRange
public static void main(String args[])
{
int random = (int)(Math.random()* 10 ) + 5;
System.out.println(random);
  }
}

Draw Line in Applet Window

import java.applet.Applet;
import java.awt.Graphics;
public class DrawLineExample extends Applet
{
public void paint(Graphics g)
{
g.drawLine(10,10,50,50);
g.drawLine(10,50,10,100);
g.drawLine(10,10,50,10);
  }
}

Create Number counter in an Applet using

import java.applet.Applet;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
public class UsingRepaintAndThreadExample extends Applet implements Runnable
{
int counter;
Thread t;
public void init()
{
counter = 0;
t = new Thread(this);
t.start();
}
public void run()
{
try
{
while(true)
{
repaint();
Thread.sleep(1000);
++counter;
}
}
catch(Exception e)
{
}
}
public void paint(Graphics g)
{                
g.setFont(new Font("Serif",Font.Bold,30));
FontMetrics fm = g.getFontMetrics();
String s = "" + counter;
Dimension d = getSize();
int x = d.width/2 - fm.stringWidth(s)/2;
int y = d.height/2;
g.drawString(s,x,y);
   }
}

No comments:

Post a Comment