Link to home
Start Free TrialLog in
Avatar of vsands
vsands

asked on

How to create a java program that generates and prints a random phone number in the form xxx-xxx-xxxx

Thats basically what i need to know in a nutshell.....
these are the parameters
-The first digit can't be a zero
-The first 3 digits can't contain an 8 or 9
-the second set of 3 digits cant begin with a zero
-the second set of 3 digits cant be greater than 610
-The first digit of the last set of digits cant be a zero

(ultimately i need it written in java form)
Avatar of zzynx
zzynx
Flag of Belgium image

What do you have already?
We're not here to write a complete programs for you. (Lots of other sites exist for that)
We're here to help you with problems you might have when writing your program
Use java.util.Random.nextInt() to generate the parts of your telephone number
ASKER CERTIFIED SOLUTION
Avatar of zzynx
zzynx
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Typo:

    tmp = digits[ rd.nextInt(10) ];

should be

    tmp = digits[ rd.nextInt(8) ];   // since 8 and 9 shouldn't be "picked"
Or easier:

StringBuffer telephoneNr = new StringBuffer();
Random rd = new Random();

// Generate first part
String tmp;
do {
   tmp = "" + (100 + rd.nextInt(900));
} while ( tmp.indexOf("8")!=-1 || tmp.indexOf("9")!=-1 );
telephoneNr.append(tmp);

telephoneNr.append("-");

// Generate 2nd part
tmp = "" + (100 + rd.nextInt(511));
telephoneNr.append(tmp);

telephoneNr.append("-");

// Generate 3rd part
tmp = "" + (1000 + rd.nextInt(9000));
telephoneNr.append(tmp);

System.out.println( telephoneNr.toString() );
Avatar of shah1d1698
shah1d1698

Try this code.. Compile & run the program.


public class Application1
{

  String finalString = null;
  public void generateNumber()
  {
    int p1 = 0, p2 = 0, p3 = 0;
    String s1 = null, s2 = null, s3 = null;


    while(true)
    {
      p1 = (int) (Math.random() * 1000);
      String temp = "" + p1;
      int tempFlag = 0;
      for(int i = 0; i < temp.length();i ++)
      {
        if(temp.charAt(i) == '8' || temp.charAt(i) == '9')
        {
          tempFlag = 1;
        }
      }
      if(p1 > 100 && tempFlag == 0)
        break;
    }

    finalString = "" + p1;

    while(true)
    {
      p2 = (int) (Math.random() * 1000);
      if(p2 > 100 && p2 < 610)
        break;
    }

    finalString = finalString + "-" + p2;

    while(true)
    {
      p3 = (int) (Math.random() * 10000);
      if(p3 > 1000)
        break;
    }

    finalString = finalString + "-" + p3;

    System.out.println(finalString);

  }

  public static void main(String args[])
  {
    Application1 app = new Application1();
    for(int i = 0; i < 1000; i++) // this will generate 1000 numbers..
    {
      app.generateNumber();
    }
  }
}