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.
Runner (int x, int y)
public static void main(String args) throws IOException
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Write the first number of the domain");
System.out.println("Write the last number of the domain");
BufferedReader nt=new BufferedReader(new InputStreamReader(System.in));
Runner RanCon=new Runner(a,b);
System.out.println("The random number is: "+x);
Made a mistake here, instead of Runner ekt it is int ekt.. still wrong results though
Care to elaborate on that 'something is wrong' part?
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
Thus, you number is Math.random * (end - start) + start, which will be between start and end (exclusive).
1) Take your number
0.0 <= x < 1.0
2) Multiply it by (end - start)
0.0 <= x * (end - start) < (end - start)
3) Add "start"
start <= x * (end - start) + start < end
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)