2013-10-28 29 views
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)); 

    } 
} 
+0

nextInt需要一个参数:http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int)'AREACODE = nextInt(700)+ 100 ;'开始你。 – Radiodef

回答

1

良好,基本实现,则需要在两个范围

  • [1生成的数字; 7]
  • [100; 742]

要在范围[m; N]你可以写:
更新(删除的Math.random())

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

HTH

+1

不要做Math.random()* 48.这是越野车。总是使用Math.nextInt(48)来代替。 – iluxa

+0

@iluxa好的,谢谢你的信息,我会更新我的帖子 – kiruwka

+0

检查了解更多信息:http://stackoverflow.com/questions/738629/math-random-versus-random-nextintint – iluxa

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 独家
所以ranNum.nextInt(7)将0和6之间运行,+ 1,使1。7
这将介于1和7之间 您
可以采取同样的本金,第二范围

0

你可以尝试下:

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

等与电话号码的其他部分。

此方法返回给定的最小值(包含)和绑定(不包含)之间的伪随机数,均匀分布的值。

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);