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 ?
            Asked
            
        
        
            Active
            
        
            Viewed 63 times
        
    2 Answers
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
- 
                    1NB. 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
- 
                    
- 
                    
- 
                    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
- 
                    
- 
                    
- 
                    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
 
    