+ 1

how do I do that if I pass by a parameter 50, I get a random number between 1 and 50?

class Random

26th Sep 2017, 1:16 AM
Anthony
3 odpowiedzi
+ 13
import java.util.Random; public class Program { static int rnd(int range) { Random obj = new Random(); return (1 + obj.nextInt(range)); } public static void main(String[] args) { for (int i = 0; i < 100; i++) System.out.println(rnd(50)); } }
26th Sep 2017, 1:56 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
Assuming @Hasty's code is what the original question is referring to: "System.out.println(rnd(50));" Will print to the console whatever the rnd() method returns. With 50 being passed as arguments. "return (1 + obj.nextInt(range));" range will be the 50 that was passed as arguments. So this is equivalent to: return 1 + obj.nextInt(50); nextInt() will return a pseudo random integer based on the number that was passed as arguments. The number in this case being 50. With 50, nextInt() is expected to return a number from 0-50. *Note* 50 is exclusive. So, it's really from 0-49. return 1 + (randNume from: 0-49) Will now return a number from 1-50. (Since the random number from 0-49 is added by 1) So, a random number from 1-50 will be printed each time the line of code "System.out.println(rand(50));" is executed.
26th Sep 2017, 2:16 AM
Rrestoring faith
Rrestoring faith - avatar
+ 3
we can't read your mind, please explain what you mean by "that". Showing the code is also helpful.
26th Sep 2017, 1:56 AM
Rrestoring faith
Rrestoring faith - avatar