# Math.Random()

• October 26th, 2011, 05:45 PM
xionyus
Math.Random()
I get the fact that it's an easy concept. The lab my teacher wanted us to construct is a random phone number generator.
The area code has to be 218, 312, or 731, it can't be anything else. He told us that we can use Math.random() for this method, but I cannot think of a way how the computer can generate those numbers unless there's an if statement. Any help? I'll post my code if needed. I just don't know the concept I am supposed to use.
• October 26th, 2011, 06:35 PM
djl1990
Re: Math.Random()
can you explain the three options: 218, 312, 731. Do you want the program to randomly pick one of these 3 and then add 8 more random digits to create a 11 digit number?
• October 26th, 2011, 06:42 PM
djl1990
Re: Math.Random()
to use the Math.Random() class firstly:

import the Random class:
Code :

`import java.util.Random;`

then in your main class section to create a Random object:
Code :

`Random rand = new Random();`

then to create for example 11 random digits ... :

Code :

```digit1 = rand.nextInt(10); digit2 = rand.nextInt(10); digit3 = rand.nextInt(10); digit4 = rand.nextInt(10); digit5 = rand.nextInt(10); digit6 = rand.nextInt(10); digit7 = rand.nextInt(10); digit8 = rand.nextInt(10); digit9 = rand.nextInt(10); digit10 = rand.nextInt(10); digit11 = rand.nextInt(10);```

rand.nextInt(10) generates a random number between 0 - 9 inclusive .

Get back if you've any more questions.
• October 26th, 2011, 10:02 PM
xionyus
Re: Math.Random()
First off, he wanted the area code to be only these, but random each time: 218, 312, 731.
The next three numbers needed like a range from 231 to 750. So I set up a variable
Then the last four numbers were to be from range 0-9999 (except for 1212).
So I set up an if statement.
The gist of the code looks like this, I left my file on my school computer.
Code :

```int areacode; areacode = //problem here, IDK what to put int middlethree; middlethree =(int)(231 + 519 * Math.random()); int lastfour; lastfour = (int)(9999 * Math.random()); if (lastfournumbers != 1212) { System.out.printf("%3d, %3d, %3d", areacode + middlethree + lastfournumbers); }```
• October 26th, 2011, 10:22 PM
Tjstretch
Re: Math.Random()
Quote:

Originally Posted by xionyus
I get the fact that it's an easy concept. The lab my teacher wanted us to construct is a random phone number generator.
The area code has to be 218, 312, or 731, it can't be anything else. He told us that we can use Math.random() for this method, but I cannot think of a way how the computer can generate those numbers unless there's an if statement. Any help? I'll post my code if needed. I just don't know the concept I am supposed to use.

`Random gen = new Random();`
`int areaCodeType = gen.nextInt(3);`
```int areaCode = -1; switch(areaCodeType) { case 0: areaCode = 218; break; case 1: areaCode = 312; break; case 2: areaCode = 731; break; }```