Michael Marhi wrote:Hi, I am new to this forum
. I have an assignment in which i have to generate a random number using Math.random(). I know how to get a random number, let's say to 100, but I don't know how to generate a random number from -100 to 100. Hope you can help me
Mohamed Sanaulla | My Blog | Author of Java 9 Cookbook | Java 11 Cookbook
Mohamed Sanaulla | My Blog | Author of Java 9 Cookbook | Java 11 Cookbook
SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Michael Marhi wrote:As i know, Math.random generates a random number from 0 to 1, so if I want to generate a random nubmer to 100, I multiply that with 100 and then I add 1, beacuse I don't want to have 0 as my random number.
Michael Marhi wrote:Thanks for your help, I managed to solve this. I hope this works combination=(int)(Math.random()*100)+1 - (int)(Math.random()*200)+1;. That should generate a random number from 1 to 100 and the right part of the code should generate a random number from 1 to 200. So if I subtract those two I get a random number between 100 and -100.
Michael Marhi wrote:Thanks for your help, I managed to solve this. I hope this works combination=(int)(Math.random()*100)+1 - (int)(Math.random()*200)+1;. That should generate a random number from 1 to 100 and the right part of the code should generate a random number from 1 to 200. So if I subtract those two I get a random number between 100 and -100.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Michael Marhi wrote:OK, the last code cleary doesn't work as I want to. How about combination=(int)(Math.random()*200)+1 - 100;? I think that should do the trick
Consider Paul's rocket mass heater. |