-6

I am making a program that will generate a random number from 1 to 10 in main and store it in specific fields but we are instructed to use Random.java. What codes shall I put in Random.java ?

mantal
  • 1,093
  • 1
  • 20
  • 38
Euqilegna
  • 1
  • 1
  • 1
    You know, you can google things like that easily. This is a useless question, since you didn't even try to figure it out on your own. – Kayaman Aug 29 '14 at 13:02

2 Answers2

0

you can try this

Random random = new Random();
int i = random.nextInt(10) + 1;
System.out.println(i);

this will genrate random integer number between 1 to 10

amit bhardwaj
  • 883
  • 2
  • 8
  • 18
  • 1
    NB. if you pass a value to `Random()` you can get the same results repeatedly which can help testing. – Holloway Aug 29 '14 at 13:04
  • you mean new Random(10) – amit bhardwaj Aug 29 '14 at 13:06
  • It doesn't have to be 10 but yes, something like that. – Holloway Aug 29 '14 at 13:32
  • try what u r saying with any number. I don't think you will get the appropriate result. – amit bhardwaj Sep 01 '14 at 06:55
  • I get exactly what I imagined. What do you think you get? – Holloway Sep 08 '14 at 08:40
  • i get a long value not integer between 1 to 10 – amit bhardwaj Sep 09 '14 at 06:11
  • Paste the code you're using here. The argument you pass to the `Random` constructor makes no difference to the scale of the numbers generated. [Random Constructor](http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#Random(long)) – Holloway Sep 09 '14 at 08:31
  • i'm only passing 10 to constructor not to nextInt() thats why i'm getting the long vale . Now i got your point and getting the same value. But if you want this type of result for testing you can easily hard code the value why use Random. – amit bhardwaj Sep 12 '14 at 08:26
  • Generally if you want a long sequence of 'random' numbers or if you want a new number for each iteration of a loop. Passing a seed will make that sequence repeatable. – Holloway Sep 12 '14 at 08:38
0
Random rand = new Random();

int  n = rand.nextInt(k) + 1;

k is the range you want and it is exclusive so you'll have to add the +1

Quantico
  • 2,398
  • 7
  • 35
  • 59