Make a variable return a random number?

I need to know how to quickly make a variable return a random number, in PHP if i wanted a variable to return a random number it'd look like this using a built in function,
(int)$my_variable = rand(0,10); // returns 0 through 10 randomly
How can i do this with Java if say my variable looks like this.
public Integer madeThisUp = 1; // Needs to be random 0-10 aswell..
I can't find any tutorials on this that make clear sense to me, :-\

2) java.util.Random has a bunch of methods that
correspond directly to common uses of random numbers.
I can't imagine a situation where Math.random would
be easier to understand.case in point, when a method is provided for you but you
try to reinvent it with:
int i = (int) (Math.random() * 10);

Similar Messages

  • Returns random number?

    Is there a code that simply returns a random number?

    Math.random(); will give you a value between 0 and 1.
    Could be multiplied with arbitrary number like (int)
    5*Math.random();
    which will give you either 0, 1 ,2, 3 or 4.Better to use java.util.Random.nextInt

  • Re: Generating a random number between 1-10;

    How do I generate a number between 1-20? I saw how to on this forum once, but I can't find it, and I don't have much time to look. Sorry for any inconvinience. What I want to do is assign to the variable x the random number.
    Thanks.
    Virum

    Random rnd = new Random();
    int x = rnd.nextInt(20)+1;

  • How I get random number between 1 and int number ?

    how can I get random number between 1 and int number
    like between 1 and 10 etc.
    10x

    Use the nextFloat() method of the Random class, this returns a random number between 0.0 and 1.0. To get and integer range from that multiply the return value of that method call by the integer range you need (in this case 10), and add the starting number you want returned in the range (1 in this case). The code below works for numbers 1-10.
    Random r = new Random();
    int x = (int)(r.nextFloat()*10) +1;

  • How to make a function return number(10,0) data type (ORACLE 10g)?

    With 10g, how to make a function return number(10,0) data type?
    here is the function, it returns a number type :
    create or replace FUNCTION Get_portfolio_Id3 (p_HistObjTable In Varchar2,p_LHISTOBJID IN NUMBER) RETURN view_cpu_STD_Asset.LPORTFOLIOITEMID%Type IS
    v_Id view_cpu_STD_Asset.LPORTFOLIOITEMID%Type;
    BEGIN
    If p_HistObjTable ='amPortfolio'
    then v_Id:=p_LHISTOBJID ;
    elsIf p_HistObjTable = 'amComputer' then
    select litemid into v_Id from smcdba.amComputer c where c.LCOMPUTERID=p_LHISTOBJID ;
    else v_Id:=-99;
    End If;
    RETURN v_Id;
    END Get_portfolio_Id3;
    Thanks.
    Message was edited by:
    user631701

    create or replace FUNCTION Get_portfolio_Id3 (p_HistObjTable In Varchar2,p_LHISTOBJID IN NUMBER) RETURN view_cpu_STD_Asset.LPORTFOLIOITEMID%Type IS
    v_Id view_cpu_STD_Asset.LPORTFOLIOITEMID%Type;
    BEGIN
    If p_HistObjTable ='amPortfolio'
    then v_Id:=p_LHISTOBJID ;
    elsIf p_HistObjTable = 'amComputer' then
    select litemid into v_Id from smcdba.amComputer c where c.LCOMPUTERID=p_LHISTOBJID ;
    else v_Id:=-99;
    End If;
    RETURN round(v_Id);
    END Get_portfolio_Id3;

  • Generate a random number and make it STAY after "save"

    I searched around this forum and found that I can use this code to generate a random number:
    //this.rawValue = Math.round(Math.random() * 1000000);
    Works great. only problem is, once I practice on the "real" form and save, close, and reopen - it changes the random number every time. I need to figure out a way to make it save the 1st number it generates when someone opens the form and types info in it....then they save and close, etc.
    Can anyone help me? Thanks!!

    Example steps:
    1. Add a hidden field to the same subform with name 'hiddenField'.
    2. First time you open 'hiddenField' rawValue will be null.
    3. where ever you run the code to generate random number use scenario like this.
    if (hiddenField.isNull) {
    this.rawValue = Math.round(Math.random() * 1000000);
    }else {
    this.rawValue = hiddenField.rawValue;
    Hope this thelps.
    SekharN

  • Applescript: how to record and return how many times a number appears when using a random number generator

    I create one rng and repeat another rng that many times like so:
    set x to (random number from 0 to 250)
    repeat x times
      set rn to (random number from 1 to 10)
    end repeat
    now what i would like to do is record and return how many times 'rn' comes up with one particular number. Any ideas?

    You could set up a list and increment the contents of a particular index each time it comes up, for example:
    set how_many to {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} -- 1 thru 10
    set x to (random number from 0 to 250)
    repeat x times
      set rn to (random number from 1 to 10)
      set item rn of how_many to (item rn of how_many) + 1
    end repeat
    return how_many

  • Need help with a JavaScript to generate random number

    Hi
    First things first. I don't know the J of JavaScript.
    When I was thinking of some readymade solution to generate a random number in Captivate, I found this on a LinkedIn forum.
    1) Add a user variable to your project called "randomNumber". It's value can be zero.
    2) Add a Text Caption with "$$randomNumber$$" in it, to check whether your script is working.
    3) Add a button to the slide. Give it an On Success Action of Execute JavaScript. Turn off it's "Continue Playing the Project" checkbox.
    4) Add the following text in the button's Script_Window:
    var objCP = document.Captivate;
    var rand = 1 + Math.floor(Math.random() * 10);
    function onButtonClick(){
    objCP.cpEISetValue('randomNumber', rand);
    onButtonClick();
    However, this is (as the poster in the forum warned) not working for Captivate 7. Can somebody please help?
    I am open for any other methods of getting the same result.
    Thanks in advance,
    Sreekanth

    Hi Sreekanth,
    When testing, make sure you are testing from a web server where the web address begins with http or https.  When setting the captivate variable "randomNumber" try this instead:
    objCP.cpEISetValue('m_VarHandle.randomNumber', rand);
    That will only work for SWF output.  If you want it to work for both HTML5 and SWF output, try this code:
    window.onButtonClick = function(){
              var rand = generateRandomNumber(1, 10);
              setCpVariable('randomNumber', rand);
    window.generateRandomNumber = function(min, max){
              var randomNum = 0;
              if(!isNaN(parseFloat(min)) && !isNaN(parseFloat(max))){
                        min = Number(min);
                        max = Number(max);
                  randomNum = Math.floor(Math.random() * (max - min + 1)) + min;
              return randomNum;
    window.setCpVariable = function (cpUserVariableName, variableValue) {
              /* Check for HTML5 vs. SWF output */
              if (typeof window.cp === 'undefined') {
                        /* We have SWF output, so Get the Captivate Object */
                        var objCp = document.getElementById('Captivate');
                        if (objCp && objCp.cpEISetValue) {
                                  /* Set the Captivate User variable with the JavaScript variable, variableValue */
                                  objCp.cpEISetValue('m_VarHandle.' + cpUserVariableName, variableValue);
              } else {
                        /* We have HTML5 output */
                        /*If variable does not exist off of the window object, then use the variables manager*/
                        if (typeof window[cpUserVariableName] === 'undefined') {
                                  if (cp.vm && cp.vm.setVariableValue) {
                                            cp.vm.setVariableValue(cpUserVariableName, variableValue);
                        } else {
                                  window[cpUserVariableName] = variableValue;
    window.onButtonClick();
    Be sure to test this from a web server or else local security will prevent the javascript from executing.
    Best,
    Jim Leichliter

  • How to make a variable global to use in all of my cfm page?

    I have a problem with the variables.
    i need to use a variable  " loginrecord" in all of my cfm pages, its created in my login.cfm and the value of this needed in other page and maybe i need to change it .
    in ASP simply we can use SESSION to make a variable global , is there any way in coldfusion ?
    also in ASP we have a command SESSION.SESSIONID ,  so return the unique number from browser and we can se it as a security check for each one of people login to our site and each one is seperate random and unique number , is there any similar in coldfusion ?
    Thanks
    Alireza

    Thanks,
    the reason at the moment i stock with this command is i need to have login information available in all the pages to check the security. the good point i had in ASP is SESSION.SESSIONID   , it make a unique number base on browser and i can check it if user loged in or no , or if loged in is the same user or other user . i couldnt find same command in coldfusion , and now i use <cflogin> but if i can find the way to have a browser session it help me in other part of my program.
    i start coldfusion new ( near a month ) i have some book and Lynda DVDs, also online sources , and in this priod i re developed one of my program from ASP to coldfusion and its work. i am happy of this and help me to develop better and faster . in compare the coldfusion developed one realy is 40% original development in size and 50% faster . i have good background of ASP in last 8 years include MCSD and developed many program for a small and big companies. but i wanna to continue with coldfusion because i found it more helpfull than ASP specialy in FLASH development .
    BTW thanks for your help

  • How do I assign images to grid cells based on their random number value?

    Hello everyone!
         I need a good point (or shove) in the correct direction.
    Background
         I've created (with previous help from this forum) a 12 x 9 random number grid which cycles through the numbers 1 to 9 a total of twelve times each. I've then created a button which shuffles the current grid's cells each time it is clicked. I now want to use 9 images that I have imported as individual symbols into the library (I have given them each their own class titled "skin1," "skin2," ... "skin9") as cell labels or the equivalent. I have also set the images up as individual movie clips (using the .Sprite class as the extended base class but keeping the actual image class names in line with their object name, i.e. the "skin1" image is the "skin1.as" class).
    Question
         How do I assign these images to the grid cells based on their respective values (ranging from 1 to 9) and have them populate the grid each time I click the "shuffle" button? So for example, in my grid the numbers 1 through 9 randomly appear 12 times each. Every time the number 4 appears in a cell, I want it to be assigned to the image "skin4" (which is just a graphic that looks like a button and has a fancy number "4" printed on it). Below is a chunk of the code I am using to draw the grid cells with:
    // Creates a grid cell when called by generateGrid().
    private funciton drawCell(_numeral:int):Sprite
              This is the code I am currently implementing to populate the grids with (although I
              don't want to use text labels as I want to fill each grid with an image according
              to its numerical value (1 to 9).
         var _label:TextField = new TextField();
         _label.multiline = _label.wordWrap = false;
         _label.autoSize = "center";
         _label.text = String(_numeral);
         // Add numerical label to cell array.
         cellLabels.push(_label);
         var _s:Sprite = new Sprite();
         _s.graphics.lineStyle(2, 0x019000);
         _s.graphics.drawRect(30, 0, cellW, CellH);
         _s.addChild(_label);
         return _s;
         While the following isn't working code, it will hopefully demonstrate what I want to achieve inside this function so I don't have to use the above snippet for text labels:
         //This will "hopefully" create an array of all 9 images by calling their classes.      var _imageArray:Array = [skin1, skin2, skin3, skin4, skin5 , skin6, skin7, skin8, skin9];      // This is what I want to happen for each cell using the above image array:      for (i = 0; i < cells; i++)      {           if (_numeral == 1)           {                // Insert skin1 image for each instance of #1 in the grid.           }           if (_numeral == 2)           {                // Insert skin2 image for each instance of #2 in the grid.           }           ...           if (_numeral == 9)           {                // Insert skin9 image for each instance of #9 in the grid.           }      } 
         Again, I don't want to use text labels. I have a custom skin graphic that I want to go over each number on the grid based on its numerical value (1 to 9). Any help with this is much appreciated!

    kglad,
         Thank you for your help with this one. Using the code below, I have successfully populated my grid cells with the desired corresponding graphics. I noticed one thing though regarding my use of the shuffle button with this particular implementation: even though the numerical values residing in each cell get shuffled, the original images remain in the grid rather than being replaced by new ones. The first code snippet below is the revised cell drawing function including your help; the second snippet shows you my simple shuffle button function (where the problem lies, I think).
    Snippet #1:
         // Creates a grid cell when called by generateGrid().
         private function drawCell(_numeral:int):Sprite
              var _label:TextField = new TextField();
              _label.multiline = _label.wordWrap = false;
              _label.autoSize = "center";
              // Creates a label that represents the numerical value of the cell.
              cellLabels.push(_label);
              var _s:Sprite = new Sprite();
              _s.graphics.lineStyle(2, 0x019000);
              _s.graphics.drawRect(30, 0, cellW, cellH);
              // Physically adds the labels to the grid.
              _s.addChild(_label);
              // Assigns a graphic class to a cell based on its numerical value.
              var _classRef:Class = Class(getDefinitionByName("skin" + _numeral));
              // Undefined variable for holding graphic classes.
              var _image:* = new _classRef();
              // Lines the images up with the grid cells.
              _image.x = 30;
              // Physically adds a graphic on top of a cell label.
              _s.addChild(_image);
              return _s;
         So far so good (although I question needing text labels at all if they are just going to remain invisible underneath the images, but enough about that for now). This next part is the reason that the images won't shuffle with the cell values, I think.
    Snippet #2:
         // When shuffleButton is clicked, this event shuffles
         // the number array and fills the cellLabels with the new values.
         private function onButtonShuffleClick(e:MouseEvent):void
              // Shuffles the number array.
              shuffle(numbers);
              // Verifies the array has been shuffled.
              trace("After shuffle:", numbers);
              // Loop replaces old cellLabels with new number array values.
              for (var i:int = 0; i < cells; i++)
                   cellLabels[i].text = String(numbers[i]);
         As you can see, it never replaces the original images that populate the grid. I tried using the _s.removeChild(image) function but that didn't work, nor would copying/pasting some of the code from snippet #1 directly into this function as it would cause another instance of the images to be placed over top of the existing ones rather than actually swapping them out. Any continued help here is greatly appreciated!
         PS Is there a quicker method for posting code into these forums without having to type it all out by hand again (i.e. copy/paste or drag/drop from my .fla or Notepad file directly into this thread)?

  • Is there any way to generate random number in CPO

    Requirement : -
    > I want  to generate a random number from set of 1-9 numbers .is there any way in cpo ?
    Thanks
    Siva

    I created a process that uses 3 steps, all of which happen inside the engine rather than having to span out to a script, so it runs a lot faster.
    Technically, it's pseudo-random...
    Predefine Output Variable "Random Number" as type "Numeric"
    Step 1:  Format Date
      Format string: fffffff 
        (that's seven lower-case letters "f")
      Original date: [Process.Start Time]
    Step 2: Format Date
      Format string: ff\0\0\0\0\0
      Original date: [Process Start Time]
    Step 3: Set Variable
      Variable to update: [Process.Variables.Output.Random Number]
      New value: ([Workflow.Format Date.Formatted Date]-[Workflow.Format Date (2).Formatted Date])/100000
    This returns a basically random number between 0 and 1 (so you can mulitply it by your maximum value) based on the numeric fraction of a second of the start time of the process.

  • Random number

    How to make sure the random number is positive??

    Is it true??public int nextInt(int n)
    Returns a pseudorandom, uniformly distributed
    int value between 0 (inclusive) and the specified
    value (exclusive), drawn from this random number
    generator's sequence. The general contract of nextInt is
    that one int value in the specified range is pseudorandomly
    generated and returned. All n possible int values are
    produced with (approximately) equal probability.>> Is it Math.random() will return a double type number??public static double random()
    Returns a double value with a positive sign,greater than or equal to 0.0 and less than 1.0. Returned
    values are chosen pseudorandomly with (approximately)
    uniform distribution from that range.(both taken from the API docs at http://java.sun.com/j2se/1.4.2/docs/api/index.html)

  • Random number issue

    I'm making a mobile game and I can't seem to generate a random number successfully
    Game.java:
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class Game extends MIDlet implements CommandListener {
    private Display theDisplay;
    private GameCanvas canvas;
    private Player p1;
    private Block[] Grid;
    static final Command exitCommand = new Command("Exit", Command.STOP, 1);
    class Player {
      public int x, y;
      public int width=60, height=15;
      public Player(int curX, int curY) {
       x = curX;
       y = curY;
    public Game() {
      setupGrid(5, 8, 5);
      p1 = new Player(90, 250);
      theDisplay = Display.getDisplay(this);
    private void setupGrid(int rows, int cols, int cellspacing) {
      Grid = new Block[200];
      int ind = 0;
      int posX = 10;
      int posY = 20;
      int colPosY;
      int colPosX;
      colPosY = posY;
      colPosX = posX;
      for(int x = 0; x < rows; x++) {
       Grid[ind] = new Block(posX, posY);
       colPosY = posY;
       for(int y = 0; y < cols; y++) {
        ind++;
        colPosX += 20+cellspacing;
        colPosY = posY;
        Grid[ind] = new Block(colPosX, colPosY);
       colPosX = posX;
       posY += 15+cellspacing;
       ind++;
    class Block {
       public int x, y;
       public int Health;
       public int r = 0, g = 0, b = 0;
       public Block(int curX, int curY) {
       x = curX;
       y = curY;
       double rand = Math.random()*5;
       if(rand > 0 && rand < 2) {
        g = 255;
        r = 0;
        b = 0;
       if(rand > 2 && rand < 4) {
        r = 255;
        g = 0;
        b = 0;
       if(rand > 3 && rand < 5) {
        b = 255;
        g = 0;
        r = 0;
    class GameCanvas extends Canvas {
      private int width;
      private int height;
      GameCanvas() {
       width = getWidth();
       height = getHeight();
      public void paint(Graphics g) {
       g.setColor(0, 0, 0);
       g.fillRect(0, 0, width, height);
       g.setColor(100, 100, 100);
       g.fillRect(p1.x, p1.y, p1.width, p1.height);
       for(int x = 0; x < Grid.length; x++) {
        if(Grid[x] != null) {
         g.setColor(Grid[x].r, Grid[x].g, Grid[x].b);
         g.fillRect(Grid[x].x, Grid[x].y, 20, 10);
      public void keyPressed(int keyCode) {
       int key = getGameAction(keyCode);
       if(key == LEFT && p1.x > 0) {
        p1.x-=4;
       else if(key == RIGHT && p1.x < canvas.width-p1.width) {
        p1.x+=4;
       repaint();
    protected void startApp() throws MIDletStateChangeException {
      canvas = new GameCanvas();
      canvas.addCommand(exitCommand);
      canvas.setCommandListener(this);
      theDisplay.setCurrent(canvas);
    public void pauseApp() { }
    public void destroyApp(boolean unconditional) { }
    public void commandAction(Command c, Displayable d) {
      if(c == exitCommand) {
       destroyApp(false);
       notifyDestroyed();
    }Game.java:58: cannot find symbol
    symbol : method random()
    location: class java.lang.Math
    double rand = Math.random()*5;
    ^
    1 error
    Line 58:
    double rand = Math.random()*5;

    b1nary wrote:
    Unfortunately, no - it won't work. Prior to posting this thread I researched different ways to generate random numbers but, apparently, the WTK only allows certain packages to be recognized.You can always write your own generator. For portability I use
    * Uniform random number generator.
    * <p>
    * Based on
    * <blockquote>
    * <pre>
    * Efficient and Portable Combined Random Number Generators
    * <a href="http://www.iro.umontreal.ca/~lecuyer">Pierre L'Ecuyer</a>
    * Communications of the ACM
    * June 1988 Volume 31 Number 6
    * </pre>
    * </blockquote>
    * @author Sabre
    public class Ecuyer
         * Constructs the generator based on two starting seeds.
         * <p>
         * Two generators using the same pair of seeds will produce
         * exactly the same sequence of pseudo random numbers.
         * @param seed1 the starting seed.
         * @param seed2 the second starting seed.
        public Ecuyer(int seed1, int seed2)
            s1 = (seed1 > 0) ? seed1 : 1;
            s2 = (seed2 > 0) ? seed2 : 1;
         * Constructs the generator based on a starting seed.
         * <p>
         * Two generators using the same seeds will produce
         * exactly the same sequence of pseudo random numbers.
         * @param seed the starting seed.
        public Ecuyer(long seed)
            this((int) ((seed >> 32) & 0x7fffffff), (int) (seed & 0x7fffffff));
         * Constructs a generator using the current time as seed.
        public Ecuyer()
            this(System.currentTimeMillis());
         * Returns the next random number
         * @return the next random number
        public double nextValue()
                // m = 2147483563, a = 40014
                int k = s1 / q1;
                s1 = a1 * (s1 - k * q1) - k * r1;
                if (s1 < 0)
                    s1 += m1;
                // m = 2147483399, a = 40692
                int k = s2 / q2;
                s2 = a2 * (s2 - k * q2) - k * r2;
                if (s2 < 0)
                    s2 += m2;
            int z = s1 - s2;
            if (z < 0)
                z += m1;
            return z * 4.656613e-10;
        static final int m1 = 2147483563;
        static final int a1 = 40014;
        static final int q1 = 53668;
        static final int r1 = 12211;
        static final int m2 = 2147483399;
        static final int a2 = 40692;
        static final int q2 = 52774;
        static final int r2 = 3791;
        private int s1;
        private int s2;
    }Make sure you test it thoroughly before committing to it.

  • Random Number Generator setSeed(); method???

    I've searched and can't get a good understanding of the setSeed() method. I am suppose to use the loop control variable to seed the random number generator inside the loop. I need to use the same input everytime I use the random generator. When I compile it says int cannot be dereferenced.
    for(int i = 0; i < array.length; i++)
    int randnum = generator.nextInt(100);
    randnum.setSeed(i);
    array[i] = randnum;
    If anyone can explain the setSeed() method that would be greatly appreciated. Thanks!

    badbro wrote:
    Thanks for your help, but leave the smart comments to yourself. They are not needed. Thats what this forum is for.All of Paul's comments were dead spot on, and if you listen to him and take his advice to heart, it will only help you. If they make you upset, well then that's your problem, isn't it? My advice: grow up.

  • Method for a random number generator???

    I need a method to generate a random number between zero and X, X being a variable set by my program. The only method I can find is Math.random(), which generates a number between 0.0 and 1.0. (Of course, I can multiply to make it an int). Can you help me out?

    I dont know if this will help not but you could do this:
    RandomNum = (int)Math.floor(Math.random() * X);
    I think that should generate your random number between 1 and variable X
    Regards,
    Carl

Maybe you are looking for