Period of Java's random generator

Hi.
I am trying to find out how long period the java generator has. I havent been able to find this info anywhere, even though I searched paper indexes, google, java.sun etc.
It looks like the random generator uses 2^48 for modulus. And I read somewhere that the multiplier is 0x5DEECE66DL, but this info is unsure. I don't know the increment factor either. With this info it would be possible to calculate the period, if it is not given.
I would appreciate any information about this.
Espen Sigvartsen
[email protected]

Have you checked out the source code for Random? It shows some of values you mention. Below is a snp of the source code. You should check it out it may provide some of the anwsers you are looking for...
    static final long serialVersionUID = 3905348978240129619L;
    private final static long multiplier = 0x5DEECE66DL;
    private final static long addend = 0xBL;
    private final static long mask = (1L << 48) - 1;
    synchronized public void setSeed(long seed) {
        this.seed = (seed ^ multiplier) & mask;
      haveNextNextGaussian = false;
    synchronized protected int next(int bits) {
        long nextseed = (seed * multiplier + addend) & mask;
        seed = nextseed;
        return (int)(nextseed >>> (48 - bits));

Similar Messages

  • How to use the random generator in java

    hey peeps, this is the class in which i am trying to implement the random generator in;
    public class Matchlist
        private studentdetails sd = new studentdetails();
        /** matchList StringBuilder stores the match list in progress */
        private StringBuilder matchList = new StringBuilder();
        private int loop = 0;
        private int matches = 0;
        public Matchlist()
            sd.createstudentdetails();
        /** Method to create the actual match list, returns the list as a string */
        public String CreateMatch()
            int g;
            int y;
                for (g = 0; g < 4; g++)//g = game
                    for (y = 17; y > -1; y--)//y = green house
                        /** Check to see if the game is empty */
                        if (sd.getgh(y).getGame(g).equalsIgnoreCase(""))
                            for (int x = 0; x < 18; x++) //x = yellow house
                                if (sd.getyh(x).getGame(g).equalsIgnoreCase(""))
                                    if (sd.getgh(y).getC_lass() != sd.getyh(x).getC_lass())
                                        /** Check to see if the person has played the other person */
                                        if (sd.getgh(y).checkPlayed(sd.getyh(x).getName()) == false)
                                            /** Set the game to the name of the opponent played */
                                            sd.getyh(x).changeGame(g, sd.getgh(y).getName());
                                            sd.getgh(y).changeGame(g, sd.getyh(x).getName());
                                            /** Build the match list step by step using append with \n at the end to create a new line */
                                            matchList.append(sd.getyh(x).getName() + " vs " + sd.getgh(y).getName() + "\n");
                                            matches++;
                                            break;
                /** Convert the stringbuilder into an actual string, then return it */
                String completeMatchList = matchList.toString();
                System.out.println(matches);
                for (int i = 0; i <18; i++)
                    sd.getyh(i).getEmptyMatches();
                    sd.getgh(i).getEmptyMatches();
                return completeMatchList;
        }what i dont understand is how to implement it to pick my matches at random using the http://java.sun.com/j2se/1.4.2/docs/api/java/util/Random.html java tutorials from here
    regards

    How to use Random ?
    First you open API then you read it, then you use it.
    You mention you try to use it but i just see a horrible nested for for for if if if loop.
    Restructure code and question and maybe it makes more sense.
    Edited by: pgeuens on 10-mrt-2008 22:58

  • Please help to write a java code for generate Random numbers

    I need a program for generate Random integer numbers by using roulette wheel theory. I search several ares, but I'm unable to find out at lease a Pseudo code for implement this. If you know or have a code for this, Please send me a mail to [email protected] or post here.

    Gagana wrote:
    I need a program for generate Random integer numbers Have a look at the java.util.Random class:
    [http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html]
    Or Google:
    [http://www.google.com/search?q=random+java]
    by using roulette wheel theory. What is that?
    ... Please send me a mail to [email protected]
    No, that defeats the purpose of a public forum. And no one is going to e-mail you (other than someone trying to sell V1AGRA).

  • Writing a class using random generator in bluej

    Hello
    Im trying to write a class for a deck of cards. Im using a random generator but I dont know how to write the instance variable.
    I have to make 4 suits heart, club, spade, dimonds. and 13 for face value. I know how to random generate numbers. Like if I were making a slot machine to give me 3 numbers in a rage from 0-10. Thats just numbers. How do I random generate values of 1-13 and have it output a random suit? Also how do I make it say if its a jack king or queen? Do I need a constructor or how would I make the card with the face value of 13 suit heart and the card be a queen.
    before jumping down my throat about this being a homework assignment...yes it is but this step Im seeking help on there is no example for this type of generating.
    Thanks for any help
    Rewind

    Well, this is far from bullet-proof, but I think gets the basic idea across. This does sampling with replacement; if you wanted to do something like shuffle a deck of cards you'll need a smarter approach than this.
    import java.util.*;
    public class RandomCards {
      public static void main(String[] args) {
        Suit suit=new Suit();
        for (int i=0; i < 10; i++) {
          System.out.println(suit.nextSuit());
      private static class Suit {
        public static final String HEART="Heart";
        public static final String DIAMOND="Diamond";
        public static final String SPADE="Spade";
        public static final String CLUB="Club";
        private final String[] SUITS={ HEART, DIAMOND, SPADE, CLUB };
        private Gen suitGen=new Gen(0,3);
        public String nextSuit() {
          return SUITS[suitGen.nextInt()];
      private static class Gen {
        private int floor,ceiling;
        private Random rand;
        public Gen(int floor, int ceiling) {
          this.floor=floor;
          this.ceiling=ceiling;
          rand=new Random();
        public int nextInt() {
          return rand.nextInt(ceiling-floor)+floor;

  • Help with java.util.Random

    Problem:
    I wanna generate random number in interval <0;1> with two "decimal number precision" (i dont know, how to expres it exactly in English.. So, here is Patern: "*X.XX*" (For ex. it might be numbers like 0.24 , 1.00 , 0.05, 0.54) ).
    I have tried to work with java.util.Random class, but i dont understood it at all, because i'm not good in Math-English terms.
    So, how can I do it? I offer duke stars for any solve. Thanks.

    First of all, read this link to understand why all floating point numbers (float, double) can't be rounded to two places of decimals.
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic|http://docs.sun.com/source/806-3568/ncg_goldberg.html]
    Consider changing your program to use integer numbers in the range of [0..100] instead. You can generate a random number in this range byRandom random = new Random();
    int randomInt = random.nextInt(101);If your problem can't be solved with this approach, you may need to tell us exactly how you plan to further process the random number.
    luck, db

  • Implementing the random generator

    Hello, i have posrted this question in the forum yesterday, and didnt get a reply, so i am reposting, hope i havent violated any of the forum rules? If i have can a mod tell me, delete it and ill try and find my old post
    The problem i am having is trying to implement thwe random generator in to my code, it hasnt been done correctly as its not printing out a list of matches based on the conditons, can someone tell me what is wrong? thanks
    import java.util.Random;
    public class Matchlist
        private studentdetails sd = new studentdetails();
        /** matchList StringBuilder stores the match list in progress */
        private StringBuilder matchList = new StringBuilder();
        private Random studentPicker = new Random();
        private int loop = 0;
        private int matches = 0;
        public Matchlist()
            sd.createstudentdetails();
        /** Method to create the actual match list, returns the list as a string */
        public String CreateMatch()
            int game;
            int yellowStudent = 0;
            int currentGame = 0;
            int matchAttempt = 0;
            while (matches < 70)
                makeMatches:
                for (game = 0; game < 4; game++)//g = game
                    for (int greenStudent = 0; greenStudent < 17; greenStudent++)
                        while (sd.getgh(greenStudent).getGame(game).equalsIgnoreCase(""))
                            matchAttempt++;
                            if (matchAttempt > 800)
                                sd = new studentdetails();
                                game = 0;
                                matches = 0;
                                break makeMatches;
                            yellowStudent = studentPicker.nextInt(17);
                            if (sd.getyh(yellowStudent).getGame(game).equalsIgnoreCase(""))
                                if (sd.getgh(greenStudent).getC_lass() != sd.getyh(yellowStudent).getC_lass())
                                    /** Check to see if the person has played the other person */
                                    if (sd.getgh(greenStudent).checkPlayed(sd.getyh(yellowStudent).getName()) == false)
                                        /** Set the game to the name of the opponent played */
                                        sd.getyh(yellowStudent).changeGame(game, sd.getgh(greenStudent).getName());
                                        sd.getgh(greenStudent).changeGame(game, sd.getyh(yellowStudent).getName());
                                        /** Build the match list step by step using append with \n at the end to create a new line */
                                        matchList.append(sd.getyh(yellowStudent).getName() + " vs " + sd.getgh(greenStudent).getName() + "\n");
                                        matches++;
                                        currentGame++;
                                        if (currentGame == 18)
                                            currentGame = 0;
                                            break;
            /** Convert the stringbuilder into an actual string, then return it */
            String completeMatchList = matchList.toString();
            System.out.println(matches);
            for (int i = 0; i < 18; i++)
                sd.getyh(i).getEmptyMatches();
                sd.getgh(i).getEmptyMatches();
            return completeMatchList;
        }

    Where is it occuring? What are the values of the variabels at that point? We can't even run your code to find out because it could be in the studentdetails class which you haven't posted. I suggest you use an IDE to set breakpoints and step through it in a debugger which will allow you to examine the state of the program a any given point and identify where the NPE is coming from.
    For Netbeans
    http://www.netbeans.org/kb/55/using-netbeans/debug.html
    For Eclipse
    http://pages.cs.wisc.edu/~cs302/resources/EclipseDebugTutorial/

  • Adding two random generated numbers together?

    I'm writing a program for a class in which we have to simulate a two die rolling. So I got the computer to generate to random numbers, and now I need to add them to get the rolled die's sum. This info will then be organized into a chart. But I have no idea how to add to randomly generted numbers together, can anybody help me??
    import java.util.Random;
    import java.util.Scanner;
    public class Test
        public static void main(String [] args)
            //Start
            Scanner in = new Scanner (System.in);
            int randDieNum1 = 0;
            int randDieNum2 = 0;
            Random randDieNum1List = new Random();
            Random randDieNum2List = new Random();
            //User Input
            System.out.print("Number of Rolls: ");
            int numToRoll = in.nextInt();
            //Testints
            //Loop
            for(int rolled = 0; rolled != numToRoll; rolled ++)
                int randDie1 = randDieNum1List.nextInt(6) + 1;
                int randDie2 = randDieNum2List.nextInt(6) + 1;
                System.out.println("RandNum1: " + randDie1);
                System.out.println("RandNum2: " + randDie2);
                int final = (int)randDie1 + (int)randDie2;
                System.out.println("Add: " + randDie1 + randDie2);
    }

    You can't call the variable "final" as that's a Java keyword. Try something like "sum" or "total".
    (Also consider just using a single Random object and calling it twice to obtain the value for each of the dice.. And don't (cast) for the fun of it or as a talisman to ward off compiler messages.)

  • Trying to build a random generator

    Hi, I am quite new to java and was wondering how do I complete building this program.
    The objective of the program is to randomly generate 100 2 digit odd integer values.
    I can generate the values but I don't know how to sieve only 100 odd integers.
    I am also supposed to find the maximum, minimum and average of all the numbers generated. I can find the average but can't seem to find maximum and minimum.
    I also need to point out the location of the maximum and minimum which I do not have a clue on how to do.
    Lastly, my program is suppose to loop when keyed in 'y' or 'Y'. I think I have done that.
    My codes are as below
    import java.io.*;
    class Question2
         public static void main (String args []) throws IOException
              BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
              Question2 theClass = new Question2();
              String strValue = "";
              int value = 0;
              int random [] = new int [100];
              int l= random.length;
              int max=0, min=0;
              int sum = 0;
              do {
              System.out.print("Enter 'Y' to Start / Begin ");
              strValue = stdin.readLine();
              if (strValue.equalsIgnoreCase("Y")){
              for(int i = 0; i<l ; i++)
                   if (i%10==0)
                        System.out.println("");
                   random[i] = randomNumber(value);//recall method to generate numbers
                   System.out.print(random[i] + " ");
                   int maximum = random;
                   max = findMaximum(maximum);//recall method for maximum
                   int minimum = random[i];
                   min = findMinimum(minimum);//recall method for minimum
                   sum = sum + random[i];
              else
              break;
              int average=0;
              average = findAverage(sum);//recall method for average
              System.out.println("\nThe average is " + average);
              System.out.println("The Maximum Number is " + max);
              System.out.println("The Minimum Number is " + min);
         }while (strValue.equalsIgnoreCase("Y"));     
              //random number generator
         public static int randomNumber (int value)
              int choose=0;
              choose = 10 + (int)(Math.random()*89);
              return choose;
         //maximum number generator
         public static int findMaximum(int maximum)
              int maxi = 0;
              if (maximum>maxi)
              maxi=maximum;
              return maxi;
         //average generator
         public static int findAverage (int sum)
              int avg = 0;
              avg = sum/100;
              return avg;
    //minimum generator
         public static int findMinimum(int minimum)
              int mini = 0;
              if (minimum<mini)
              mini = minimum;
              return mini;
    Thank you.

    Yes, but it guarantees that the process will be
    complete after 100 iterations. The discarding
    strategy will be completed in 200 iterations, on
    average, and there is no guarantee that once in a
    while, it will not take 1000 iterations.Pshaw. It's not that expensive to generate a new
    number. Heck, Random.nextInt(int) numbers are
    generated by throwing away numbers. There's a chance
    that it will never return.
    And if you are worried about that, I've got a server
    to sell you.
    ~CheersI myself (almost) always prefer clarity over performance. In this case,
    I think 2 * n + 1 produces both. You may say that I overdo it, for such
    a simple exercise. This I don't dispute. By the way, the way nextInt() is
    implemented is irrelevant, don't we like encapsulation anymore?

  • Random Generator semantic error

    I need to create a public class method for a class RandomGenerator called getRandomNumber() which takes a single int argument and returns a random number between 1 and its argument (inclusive) which is generated by sending a suitable nextInt() message to the class variable rand.
    This is my code so far.
    import java.util.Random;
    import ou.*;
    * Class RandomGenerator - write a description of the class here.
    * @author (your name)
    * @version (a version number or a date)
    public class RandomGenerator
         /* instance variables */
         private int exampleVar; // replace this example variable with your own
          * Default constructor for objects of class RandomGenerator
         public RandomGenerator()
              super();
         private Random rand = new Random();
        public int getRandomNumber(int num)
            int ranum;
            String StringNum;
            StringNum = OUDialog.request("Please enter a number");
            num = Integer.parseInt(StringNum);
            if (num <=0)
            StringNum = OUDialog.request("Please enter a positive integer");
            return
            ranum = rand.nextInt(num);
            When I test it I get the error 'Semantic error: Cannot reach instance method: getRandomNumber( int ) from static context: RandomGenerator'
    I don't understand what the error means.

    When calling methods, you can either call the method on an object (an instance of a class), or directly on the class. Calling a method directly on the class assumes that the method is static, which means that the method is shared among all instances of the class, rather than each instance having it's own version.
    For instance, this line in your code:
    num = Integer.parseInt(StringNum);You called the parseInt() method of the Integer class statically, because parseInt() is a static method. You don't need a previous integer value to call parseInt(). Now the Integer class also has a method called intValue() which returns the current value of the Integer as an int. Obviously, if there's no int value stored in the integer, calling that method would be useless:
    Integer.intValue(); //no value to return
    Integer anInteger = new Integer(3);
    int anInt = anInteger.intValue(); //returns 3So since your getRandomNumber() method is not static, you must have an instance of the RandomGenerator class to call it on, like the post above shows.

  • Seeding the random generator

    I have program that uses random but each time i start the program i get the same sequence. I need to seed and start the rnd-generator but java doesnt support true random. Can anyone tell where i can find such a generator?

    True randomness requires a hardware solution that takes input from physical processes (such as radio "white noise"). I think somebody said that certain PCs or chipsets have such hardware, but in general you won't have that option available to you.
    java.util.Random and Math.random use a seed you provide, or the system clock if you don't provide a seed. If you use the same seed twice, you'll get the same sequence of numbers both times.
    One common error when generating random numbers is to reseed the generator each time in a loop. For instance for (int ix  0; ix  < 100; ix++) {
        Random rand = new Random();
        int i = rand.nextInt(10);
    } This will probably produce the same number 100 times, or maybe one number N times and another number 100 - N times. The reason is that every time you create a new Random that way, you're seeding it with the system clock and starting from that sequence's first number. The system clock doesn't have time to change, or maybe changes once, during the time it takes to run through one loop iteration, so you keep starting the same sequence over, or maybe get the first number of two different sequences. The solution is to move the new Random() outside the loop. If it were a member variable, you'd probably want to make it static.
    The above doesn't sound like your problem, but I present it because the solution to the problem you are having could lead to the above situation.
    As someone already said, if the problem is that you get the same sequence on multiple runs of the program, then just use the system time to seed the PRNG, either explicitly or by not specifying a seed. As long as it takes at least 10 ms between one program startup and the next, you'll get different sequences.
    Finally, you might want to look into [url http://java.sun.com/j2se/1.4.2/docs/api/java/security/SecureRandom.html]SecureRandom. It has better random properties than java.util.Random or Math.random, and I think if your computer does have true random hardware attached, it will use that, or can be told to use it.
    &para;

  • Random generator for given distribution function

    I need to write a random generator, not for normal distribution only but for any distribution function.
    That function can be a black-box distribution function, or that can be a table [ x | f(x) ].
    For those not familiar with this term, distribution function is f(x) that returns the posibility of that the radmon number is lesser than x. f(-inf) = 0, f(+inf) = 1, x > y => f(x) >= f(y).

    I don't have my stats text books with me, but Google is your friend! :-)
    This looks like what we coverd in stats class:
    http://www.mathworks.com/access/helpdesk/help/toolbox/stats/prob_di7.shtml
    >
    Inversion
    The inversion method works due to a fundamental theorem that relates the uniform distribution to other continuous distributions.
    If F is a continuous distribution with inverse F^-1, and U is a uniform random number, then F^-1(U) has distribution F.
    So, you can generate a random number from a distribution by applying the inverse function for that distribution to a uniform random number. Unfortunately, this approach is usually not the most efficient.
    How do you get a random number from a uniform distribution? Easy: with java.util.Random, or some other java math package (I like http://hoschek.home.cern.ch/hoschek/colt/index.htm).
    The first link details some other methods, as will most stats text books.

  • Random generator question

    I can't understand how to use Random generator when it requires minimum number and maxium number.
    import java.util.Random;
    public class Random
    public static void main(String[]args)
    Random generator = new Random();
    int num1;
    num1 = generator.nextInt(15) + 20;
    System.out.println("From 20 to 34: " +num1);
    num1 = generator.nextInt(20)-10;
    System.out.println("From -10 to 9: " +num1);
    }Can someone explain to me how the first Random generator is from 20 to 34 and the second Random genertor is rom -10 to 9?
    Edited by: CloneMe on May 31, 2009 1:06 PM

    CloneMe wrote:
    num1 = generator.nextInt(15) + 20;
    java.util.Random's nextInt() method generates a pseudo-random integer value that falls within 0 and the value supplied as the argument but not including that value.

  • Random generator

    Peeps, to the following match list how do i implent the random generator so that each match is picked at random but still checks the following conditions? help is desperatley needed, i tried using the guide
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/Random.html
    but to no avail - im REALLY stuck, thanks
    public class Matchlist
        private studentdetails sd = new studentdetails();
        /** matchList StringBuilder stores the match list in progress */
        private StringBuilder matchList = new StringBuilder();
        private int loop = 0;
        private int matches = 0;
        public Matchlist()
            sd.createstudentdetails();
        /** Method to create the actual match list, returns the list as a string */
        public String CreateMatch()
            int g;
            int y;
                for (g = 0; g < 4; g++)//g = game
                    for (y = 17; y > -1; y--)//y = green house
                        /** Check to see if the game is empty */
                        if (sd.getgh(y).getGame(g).equalsIgnoreCase(""))
                            for (int x = 0; x < 18; x++) //x = yellow house
                                if (sd.getyh(x).getGame(g).equalsIgnoreCase(""))
                                    if (sd.getgh(y).getC_lass() != sd.getyh(x).getC_lass())
                                        /** Check to see if the person has played the other person */
                                        if (sd.getgh(y).checkPlayed(sd.getyh(x).getName()) == false)
                                            /** Set the game to the name of the opponent played */
                                            sd.getyh(x).changeGame(g, sd.getgh(y).getName());
                                            sd.getgh(y).changeGame(g, sd.getyh(x).getName());
                                            /** Build the match list step by step using append with \n at the end to create a new line */
                                            matchList.append(sd.getyh(x).getName() + " vs " + sd.getgh(y).getName() + "\n");
                                            matches++;
                                            break;
                /** Convert the stringbuilder into an actual string, then return it */
                String completeMatchList = matchList.toString();
                System.out.println(matches);
                for (int i = 0; i <18; i++)
                    sd.getyh(i).getEmptyMatches();
                    sd.getgh(i).getEmptyMatches();
                return completeMatchList;
        }

    jermaindefoe wrote:
    lol, ok then, the code above is a match list generator that works on a set of conditions, the conditions dont need to be mentioned at the moment as that part of the code works, what does need to be mentioned though is the fact that in another class there is a student list, 2 lots of groups with 18 students each. what i want is to implement the random generator on my code so that players are picked at random and then the conditons are checked, if a match isnt found then another is picked randomly
    i just dont no how, i really would like some help if poss?Are you allowed to use java.util.Random?

  • Writing a java program for generating .pdf file with the data of MS-Excel .

    Hi all,
    My object is write a java program so tht...it'll generate the .pdf file after retriving the data from MS-Excel file.
    I used POI HSSF to read the data from MS-Excel and used iText to generate .pdf file:
    My Program is:
    * Created on Apr 13, 2005
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package forums;
    import java.io.*;
    import java.awt.Color;
    import com.lowagie.text.*;
    import com.lowagie.text.pdf.*;
    import com.lowagie.text.Font.*;
    import com.lowagie.text.pdf.MultiColumnText;
    import com.lowagie.text.Phrase.*;
    import net.sf.hibernate.mapping.Array;
    import org.apache.poi.hssf.*;
    import org.apache.poi.poifs.filesystem.*;
    import org.apache.poi.hssf.usermodel.*;
    import com.lowagie.text.Phrase.*;
    import java.util.Iterator;
    * Generates a simple 'Hello World' PDF file.
    * @author blowagie
    public class pdfgenerator {
         * Generates a PDF file with the text 'Hello World'
         * @param args no arguments needed here
         public static void main(String[] args) {
              System.out.println("Hello World");
              Rectangle pageSize = new Rectangle(916, 1592);
                        pageSize.setBackgroundColor(new java.awt.Color(0xFF, 0xFF, 0xDE));
              // step 1: creation of a document-object
              //Document document = new Document(pageSize);
              Document document = new Document(pageSize, 132, 164, 108, 108);
              try {
                   // step 2:
                   // we create a writer that listens to the document
                   // and directs a PDF-stream to a file
                   PdfWriter writer =PdfWriter.getInstance(document,new FileOutputStream("c:\\weeklystatus.pdf"));
                   writer.setEncryption(PdfWriter.STRENGTH128BITS, "Hello", "World", PdfWriter.AllowCopy | PdfWriter.AllowPrinting);
    //               step 3: we open the document
                             document.open();
                   Paragraph paragraph = new Paragraph("",new Font(Font.TIMES_ROMAN, 13, Font.BOLDITALIC, new Color(0, 0, 255)));
                   POIFSFileSystem pofilesystem=new POIFSFileSystem(new FileInputStream("D:\\ESM\\plans\\weekly report(31-01..04-02).xls"));
                   HSSFWorkbook hbook=new HSSFWorkbook(pofilesystem);
                   HSSFSheet hsheet=hbook.getSheetAt(0);//.createSheet();
                   Iterator rows = hsheet.rowIterator();
                                  while( rows.hasNext() ) {
                                       Phrase phrase=new Phrase();
                                       HSSFRow row = (HSSFRow) rows.next();
                                       //System.out.println( "Row #" + row.getRowNum());
                                       // Iterate over each cell in the row and print out the cell's content
                                       Iterator cells = row.cellIterator();
                                       while( cells.hasNext() ) {
                                            HSSFCell cell = (HSSFCell) cells.next();
                                            //System.out.println( "Cell #" + cell.getCellNum() );
                                            switch ( cell.getCellType() ) {
                                                 case HSSFCell.CELL_TYPE_STRING:
                                                 String stringcell=cell.getStringCellValue ()+" ";
                                                 writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
                                                 phrase.add(stringcell);
                                            // document.add(new Phrase(string));
                                                      System.out.print( cell.getStringCellValue () );
                                                      break;
                                                 case HSSFCell.CELL_TYPE_FORMULA:
                                                           String stringdate=cell.getCellFormula()+" ";
                                                           writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
                                                           phrase.add(stringdate);
                                                 System.out.print( cell.getCellFormula() );
                                                           break;
                                                 case HSSFCell.CELL_TYPE_NUMERIC:
                                                 String string=String.valueOf(cell.getNumericCellValue())+" ";
                                                      writer.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
                                                      phrase.add(string);
                                                      System.out.print( cell.getNumericCellValue() );
                                                      break;
                                                 default:
                                                      //System.out.println( "unsuported sell type" );
                                                      break;
                                       document.add(new Paragraph(phrase));
                                       document.add(new Paragraph("\n \n \n"));
                   // step 4: we add a paragraph to the document
              } catch (DocumentException de) {
                   System.err.println(de.getMessage());
              } catch (IOException ioe) {
                   System.err.println(ioe.getMessage());
              // step 5: we close the document
              document.close();
    My Input from MS-Excel file is:
         Planning and Tracking Template for Interns                                                                 
         Name of the Intern     N.Kesavulu Reddy                                                            
         Project Name     Enterprise Sales and Marketing                                                            
         Description     Estimated Effort in Hrs     Planned/Replanned          Actual          Actual Effort in Hrs     Complexity     Priority     LOC written new & modified     % work completion     Status     Rework     Remarks
    S.No               Start Date     End Date     Start Date     End Date                                        
    1     setup the configuration          31/01/2005     1/2/2005     31/01/2005     1/2/2005                                        
    2     Deploying an application through Tapestry, Spring, Hibernate          2/2/2005     2/2/2005     2/2/2005     2/2/2005                                        
    3     Gone through Componentization and Cxprice application          3/2/2005     3/2/2005     3/2/2005     3/2/2005                                        
    4     Attend the sessions(tapestry,spring, hibernate), QBA          4/2/2005     4/2/2005     4/2/2005     4/2/2005                                        
         The o/p I'm gettint in .pdf file is:
    Planning and Tracking Template for Interns
    N.Kesavulu Reddy Name of the Intern
    Enterprise Sales and Marketing Project Name
    Remarks Rework Status % work completion LOC written new & modified Priority
    Complexity Actual Effort in Hrs Actual Planned/Replanned Estimated Effort in Hrs Description
    End Date Start Date End Date Start Date S.No
    38354.0 31/01/2005 38354.0 31/01/2005 setup the configuration 1.0
    38385.0 38385.0 38385.0 38385.0 Deploying an application through Tapestry, Spring, Hibernate
    2.0
    38413.0 38413.0 38413.0 38413.0 Gone through Componentization and Cxprice application
    3.0
    38444.0 38444.0 38444.0 38444.0 Attend the sessions(tapestry,spring, hibernate), QBA 4.0
                                       The issues i'm facing are:
    When it is reading a row from MS-Excel it is writing to the .pdf file from last cell to first cell.( 2 cell in 1 place, 1 cell in 2 place like if the row has two cells with data as : Name of the Intern: Kesavulu Reddy then it is writing to the .pdf file as Kesavulu Reddy Name of Intern)
    and the second issue is:
    It is not recognizing the date format..it is recognizing the date in first row only......
    Plz Tell me wht is the solution for this...
    Regards
    [email protected]

    Don't double post your question:
    http://forum.java.sun.com/thread.jspa?threadID=617605&messageID=3450899#3450899
    /Kaj

  • How to create a new user in IDM 8.1 with random generated password?

    Hi, i want create a new user using a modified tabbed user fom that cannot ask for password and confirm password to the administrator but randomly generate a new password (only when the form is opened in user creation) according to password policy and display it on the form.
    I think it is possible because Reset User Password Form does it, but i don't know how put this kind og logic in an other form.
    thanks
    Marco

    If you want to generate a users password randomly then you could take a look at the com.waveset.provision.PasswordGenerator class inside the Identity Mgr REF kit. Here's an example:
    <Rule name='generateRandomPassword'>
           <Comments>generate a random password</Comments>
           <RuleArgument name='accountId' value='Configurator'>
             <Comments>accountId of the user</Comments>
             <String>Configurator</String>
           </RuleArgument>
           <RunAsUser>
             <ObjectRef type='User' id='#ID#Configurator' name='Configurator'/>
           </RunAsUser>
           <block trace='true'>
             <defvar name='session'>
               <or>
                 <ref>context</ref>
                 <ref>display.session</ref>
               </or>
             </defvar>
             <defvar name='wsuser'>
               <invoke name='getObject' class='com.waveset.ui.FormUtil'>
                 <ref>session</ref>
                 <s>User</s>
                 <ref>accountId</ref>
               </invoke>
             </defvar>
              <defvar name='pwgenerator'>
               <new class='com.waveset.provision.PasswordGenerator'>
                 <ref>session</ref>
               </new>
             </defvar>
             <invoke name='generatePassword'>
               <ref>pwgenerator</ref>
               <ref>wsuser</ref>
             </invoke>
           </block>
        </Rule> You'll want to take the password.password field and inside the Default event handler check to see if waveset.id is null, if it is then call the Rule above.
    HTH,
    Paul

Maybe you are looking for