0

我正在尝试创建一个具有范围的随机电话号码。格式为 (xxx)-xxx-xxx,区号不以 0、8 或 9 开头,下一组三个在 100-742 范围内,最后一组 4 可以是任何数字。我将如何创建前两个部分?任何帮助,将不胜感激。谢谢!

import java.util.*;
import java.text.*;

public class PhoneNumber{
    public static void main(String[] arg){
        Random ranNum = new Random();
        //int areaCode = 0;
        //int secSet = 0;
        //int lastSet = 0;
        DecimalFormat areaCode = new DecimalFormat("(000)");
        DecimalFormat secSet = new DecimalFormat("-000");
        DecimalFormat lastSet = new DecimalFormat("-0000");
        //DecimalFormat phoneNumber = new DecimalFormat("(###)-###-####");
        int i = 0;
        //areaCode = (ranNum.nextInt()); //cant start with 0,8,9
        //secSet = (ranNum.nextInt()); // not greater than 742 and less than 100
        //lastSet = (ranNum.nextInt(999)) + 1; // can be any digits


        i = ranNum.nextInt();
        System.out.print(areaCode.format(i));
        i = ranNum.nextInt();
        System.out.print(secSet.format(i));
        i = ranNum.nextInt();
        System.out.print(lastSet.format(i));

    }
}
4

4 回答 4

1

好吧,基本上,您需要生成两个范围内的数字

  • [1; 7]
  • [100; 第742章]

在 [m; 范围内有随机整数;n] 你可以写:
更新(删除 Math.random())

int numberInRange = m + new Random().nextInt(n - m + 1);

高温高压

于 2013-10-28T23:02:45.963 回答
1

1,2,3,4,5,6,7 产生 7 个不同的值

    ranNum.nextInt(7)+1; //So 1 is your lowest number and 7 is the number of different solutions

nexInt 将介于 0 和 intPassed Exclusive 之间因此
ranNum.nextInt(7)在 0 和 6 之间运行,+ 1 使 1 .. 7
这将在 1 和 7 之间
您可以将相同的主体用于第二个范围

于 2013-10-28T23:04:40.550 回答
0

只需制作一个大于 99 且小于 800 的随机数,然后下一个将大致相同的方式。

 Random rand = new Random();

// add 1 to make it inclusive
                                   max   min
int firstRandomSet = rand.nextInt((799 - 100) + 1) + 100; 
//none starts with 0,8, or 9


int secondRandomSet = rand.nextInt((742 - 100) + 1) + 100; 
//produces anything from 100-742

要获得 0001 - 9999 的数字,您必须要有创意。

int maxValues= 9999;

       int thirdRandomSet = rand.nextInt(maxValues);

       System.out.printf("%04d\n", thirdRandomSet);
于 2013-10-28T23:12:04.753 回答
0

你可以试试下一个:

int sec = java.util.concurrent.ThreadLocalRandom.current().nextInt(100, 743);

以此类推与电话号码的其他部分。

此方法返回给定最小值(包括)和边界(不包括)之间的伪随机均匀分布值。

于 2013-10-28T23:06:31.407 回答