1. Member Join Date
Nov 2009
Posts
2
Rep Power
0

## Java random number

Hey everyone, I am a beginner at Java ( totally ). And i wanted to create my first java program with the little things I know that will generate a random number in a defined domain I choose. ( eg a random number between [x,y] )

But something is wrong and I dont know why and where to look for a solution, so I post here.
Thanks very much, please explain me what is my fault.

import java.io.*;
class Runner
{
int a;
int b;
int x;
Runner (int x, int y)
{
a=x;
b=y;
}
Runner ekt()
{
x=a+(int)(Math.random()*b);
return x;
}
}

class RanNum
{
public static void main(String[] args) throws IOException
{
int x;
int a;
int b;
System.out.println("Write the first number of the domain");
System.out.println("Write the last number of the domain");
Runner RanCon=new Runner(a,b);
x=RanCon.ekt();
System.out.println("The random number is: "+x);
}
}  Reply With Quote

2. Member Join Date
Nov 2009
Posts
2
Rep Power
0

## Made a mistake here, instead of Runner ekt it is int ekt.. still wrong results though  Reply With Quote

3. ## Care to elaborate on that 'something is wrong' part?

kind regards,

Jos  Reply With Quote

4. ## When you say "random number", do you mean a random integer, or a random floating point value? From your code, it seems a random integer, so I'll go with that.

In your code you ask for two values, the "start" and "end" value. Math.random() returns a number, x, such that 0.0 < x < 1.0

So, to return a number between start and end (exclusive), do the following

Java Code:
```1) Take your number
0.0 <= x < 1.0
2) Multiply it by (end - start)
0.0 <= x * (end - start) < (end - start)
start <= x * (end - start) + start < end```
Thus, you number is Math.random * (end - start) + start, which will be between start and end (exclusive).

To have the value between start and end (inclusive), multiply by (end - start + 1) and take the floor of the value.

So at step 3 you get
start <= x * (end - start + 1) + start < end + 1

After you take the floor
start <= Math.floor(x * (end - start + 1) + start) <= end

Note: this method will not work (due to overflow) if (end - start + 1) causes an overflow.

For example, if "start" is Integer.MIN_VALUE and "end" is Integer.MAX_VALUE, (end - start + 1) is ZERO!

end = 2^31 - 1
start = -2^31
-start = -2^31 (incorrectly)

end - start + 1 = (2^31 - 1) - 2^31 + 1 = 0 (big problem)
Last edited by CodesAway; 11-22-2009 at 06:22 AM.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•