Java Program to generate random numbers

Hi Folks. My friend asked for a java program which can help in generating the random numbers because he's writing some sort of game. Well, I'm not a big Java fan as I still love C\C++ to write codes however after writing a revolutionary code like Space Eater Virus in Java many friends suggested me to migrate from C language to Java. I left this decision on time as of now. In order to solve the problem of my buddy I randomly or you can say shamelessly got a code from internet which was written for the same purpose. Here I'm sharing that code.....

public class Random
{
    private static long seed = 13;
    private static long a;
    private static long c;
    private static long m;

    public static void random_init(long s) {
if (s != 0) seed = s;
    }

    public static long random() {
seed = (a*seed + c)%m;
return seed;
    }

    public static void main(String[] args) {
if (args.length != 4) {
   System.out.println("usage: you must enter values for a, c, m, seed");
   return;
}
a = Long.parseLong(args[0]);
c = Long.parseLong(args[1]);
m = Long.parseLong(args[2]);
long s = Long.parseLong(args[3]);
random_init(s);
for (int k = 0; k < m-1; k++) {
   System.out.println(random());
   if (k % 8 == 7) { // after 8 elements go to a new line
System.out.println();
try {
   Thread.sleep(1000); // sleep for a second
} catch (Exception e) {
   System.out.println(e.getMessage());
       }

   }
}
    }
}

If you're having troubles in compiling the code then take a look at How to Compile the JAVA Program.

Keep Coding. :)
Previous
Next Post »