0

So, I am fairly new to programming and I started learning about Math.random. I am trying to code a program that will print values in between 4 - 12 but i can't seem to print only the values inside that range. It prints 13 which i don't want to

My Code:

public class MathRandom{
    public static void main(String[] args){

        for(int x = 0; x < 10; x++){ //Just to test what numbers are displayed
        System.out.println((int) (Math.random() * 10) + 4);

        }
    }
}

Did I miss something? thanks in advance for the help

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
5ilv3r
  • 3
  • 1
  • Create an array of desired elements (4 - 12) and then select random index from it. Int[] ArrayVariable = [4, 5, ..., 12]; random = from 0 to count of elements in ArrayVariable system.out.println(ArrayVariable[random]); – Nubian Aug 30 '17 at 13:02
  • google is your friend: ***4.710.000 results (0,59 Seconds)*** – ΦXocę 웃 Пepeúpa ツ Aug 30 '17 at 13:04
  • Bro, you must be blind. I asked how to generate ANY RANDOM NUMBER BETWEEN ANY TWO VALUES. NOT ARRAY!! It's COMPLETELY DIFFERENT – 5ilv3r Aug 30 '17 at 14:06

1 Answers1

0

Change the line to this:-

System.out.println((int) (Math.random() * 9) + 4);

This will generate a random number from 0-8, and then add 4 to it, meaning the results will be from 4-12.

Steve Smith
  • 2,244
  • 2
  • 18
  • 22
  • May I just ask, but why is it 9 instead of 10? Can you explain so that I can understand how it works? – 5ilv3r Aug 30 '17 at 13:08
  • 4,5,6,7,8,9,10,11,12 <--- 9 distinct values – CSmith Aug 30 '17 at 13:14
  • `Math.random() * 9` generates the numbers 0-8 (i.e. one less than the 9). `Math.random() * 10` generates the numbers 0-9. https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random() Note that there are better ways to get random numbers though. – Steve Smith Aug 30 '17 at 13:15
  • OHHHH I GET IT NOW! How dumb of me to not notice. Thank you VERY much for telling me – 5ilv3r Aug 30 '17 at 13:38