Generating Phone Number in Java

Problem:

Write an application that creates and prints a random phone number of the form xxx-xxx-xxxx. Include the dashed in the output. Do not let the first three digits contain an 8 or 9. And make sure that the second set of three digits is not greater than 742 (i.e. ≤ 742). Hint: Think through the easiest way to construct he phone number. Each digit does not have to be determined separately.

Output:

016-326-5981

Solution:

import java.util.Random;
public class Problem4 {

   public static void main(String args[])
   {
     Random generator = new Random();


     // Generate 3 random numbers between 0 & 7 for the first part of the phone number
  int one = generator.nextInt(8);
  int two = generator.nextInt(8);
  int three = generator.nextInt(8);
  int fourtosix = generator.nextInt(743);
  int seventoten = generator.nextInt(10000);
  String sOne = "" + (one);
  String sTwo = "" + (two);
  String sThree = "" + (three);
  String sFourtosix = "";
  String sSeventoten = "";
  if (fourtosix >= 0 && fourtosix < 10)
   sFourtosix = "00" + (fourtosix);
   else
    if(fourtosix < 100)
     sFourtosix = "0" + (fourtosix);
    else
     sFourtosix = "" + (fourtosix);
     
  if (seventoten >= 0 && seventoten < 10)
   sSeventoten = "000" + (seventoten);
   else
    if(seventoten < 100)
     sSeventoten = "00" + (seventoten);
    else
     if(seventoten < 1000)
      sSeventoten = "0" + (seventoten);
      else
       sSeventoten = "" + (seventoten);  
 

  //Print the phonenumber with this format xxx-xxx-xxxx
  System.out.printf(sOne + sTwo + sThree +"-" +sFourtosix + "-" + sSeventoten);
   }


}


1 comment :

  1. Thanks a lot for sharing us about this update. Hope you will not get tired on making posts as informative as this. Modern Behaviour WA

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact