-1

I am trying to generate a random number between a given range and 0. The code given below helped me to generate a number between the given range.

(int)(Math.random() * 13 + 4);

Is it possible to modify this code to generate a value between 4 and 10 and also 0

Amit Bera
  • 7,075
  • 1
  • 19
  • 42
mehani97
  • 21
  • 5
  • The question hasn't a real answer in the linked page: it doesn't want a random number in a range but a random number in a range *plus* a value outside that range. – Pino Mar 21 '19 at 09:11

3 Answers3

1

use this for generate a value between 4 and 10

 public static double getRandomDoubleBetweenRange(int 4, int 10){
    double x = (Math.random()*((10-4)+1))+4;
    return x;
  }
0

I suspect that this is a homework question so I won't spoonfeed you with the correct answer but give you the tools you need to answer it yourself:

public static double random()

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

Source: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#random--

Casting a double to an int performs a narrowing primitive conversion. In the range you use and for positive numbers, you can just treat it like a floor (removing the numbers after the decimal point).

If you want to know about the details, see: https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3

Konrad Höffner
  • 11,100
  • 16
  • 60
  • 118
0

Something like this would do the cause.

//stream 3 random numbers from 0 to 10 and pick any of them
int random = new Random().ints(3, 0, 11).findAny().getAsInt(); 
//print it
System.out.println(random);

UPDATE 2:

// make a list of 0 and 4-10
 List<Integer> list = Arrays.asList(0,4,5,6,7,8,9,10);
 // used for picking random number from within a list
 Random random = new SecureRandom();
 // get random index element from a list
 int randomNumber = list.get(random.nextInt(list.size()));
 // print
 System.out.println(randomNumber);
MS90
  • 1,219
  • 1
  • 8
  • 17