Jump to content


Random Number Generator


  • Please log in to reply
1 reply to this topic

#1 nujumkey

nujumkey

    Member

  • Members
  • PipPip
  • 10 posts

Posted 12 February 2012 - 03:18 PM

does anyone know what the code is to have java create a random number for you?
i cant remember it, i tried Math.random but thats an error.
i think it was something along those lines though D:

#2 nyccanuck

nyccanuck

    Advanced Member

  • Members
  • PipPipPip
  • 78 posts

Posted 13 February 2012 - 03:01 AM

View Postnujumkey, on 12 February 2012 - 03:18 PM, said:

does anyone know what the code is to have java create a random number for you?
i cant remember it, i tried Math.random but thats an error.
i think it was something along those lines though D:


import java.util.Random;
public class RandomNumbers
{
public static void main (String[] args)
{
Random rand = new Random();

int num1, num2, num3;
float num4;

num1 = rand.nextInt();
System.out.println("A random integer:\t" + num1);

num2 = rand.nextInt(10);
System.out.println("From 0 - 9:\t\t\t" + num2);

num3 = rand.nextInt(10) + 1;
System.out.println("From 1 - 10:\t\t" + num3);

num4 = rand.nextFloat();
System.out.println("A random float:\t\t" + num4);

num4 = rand.nextFloat() * 6;
System.out.println("0.0 to 0.5999999:\t" + num4);
}
}

Output:

--------------------Configuration: <Default>--------------------
A random integer: -384100802
From 0 - 9: 2
From 1 - 10: 3
A random float: 0.9744109
0.0 to 0.5999999: 3.0028782

Process completed.