Shop OBEX P1 Docs P2 Docs Learn Events
Random Number Won't Divide — Parallax Forums

Random Number Won't Divide

GibithGibith Posts: 18
edited 2008-01-13 18:51 in General Discussion
I'm trying to work with the random number generator so I wrote some test code to try and understand it. I wanted this program to generate a random number and divide that number by 10, but when I run the program I get the same numbers as if the number wasn't divided by ten.
Here is the code:

import stamp.core.*;
import java.util.*;

class RandomIntTestDrive{
  public static Random r1 = new Random(4);
  public static Random r2 = new Random(3);
  public static final int MAX_RAND = 10;
  public static void main() {

    System.out.println("Press 'r' to generate a random number between 1 and 10");
    System.out.println(MAX_RAND);
    while(true){
      switch(Terminal.getChar()){
      case 'r':
        int test3 = r1.next();
        int test4 = r2.next();
        int test1 = test3 / 10;
        int test2 = test4 / 10;
        System.out.println(test1 + " " + test2);
        System.out.println(25 / 5);
        break;
        }
        }
        }
        }






What I ultimately need to do is get the generator to generate a number between one and ten. So if you could tell me how to do that as well I would appreciate it.

Comments

  • Peter VerkaikPeter Verkaik Posts: 3,956
    edited 2008-01-13 18:07
    Try to replace the line
    ········System.out.println(test1·+·"·"·+·test2);

    by
    ········· System.out.print(test1);
    ········· System.out.print(' ');
    ········· System.out.println(test2);

    because I think the original line tries to create a temporary string where the values
    of test1 and test2 are treated as string addresses, which they are not.
    System.out has a number of print methods, each taking a different type of argument,
    you can't mix types as you can in pc java.

    regards peter
  • GibithGibith Posts: 18
    edited 2008-01-13 18:35
    Thanks that worked. I still need to now how to limit the numbers generated between one and ten. Also is there any way to round the int up and not just drop the last digit.
  • Peter VerkaikPeter Verkaik Posts: 3,956
    edited 2008-01-13 18:44
    MAX_RAND is set by Random class to 0x7FFF.
    so next() returns a pseudorandom number from 0 to 0x7FFF

    The easy way to generate numbers between 1 and 10 is
    ········int·test1·=·(r1.next() % 10) + 1;
    ········int·test2·=·(r2.next() % 10) + 1;
    You then also do not need to divide by 10

    To use rounded values:
    ········int·test1·=·((r1.next()+5) % 10) + 1;
    ········int·test2·=·((r2.next()+5) % 10) + 1;


    regards peter
  • GibithGibith Posts: 18
    edited 2008-01-13 18:51
    Thanks that worked great!
Sign In or Register to comment.