以随机数打印0

时间:2013-10-16 17:06:46

标签: java math random generator

我最初用3个变量编写了这个程序,每个变量对应一个,但是, 我无法让java打印最后四个数字的0007之类的数字。它只会打印XXX-XXX-7而不是XXX-XXX-0007。如何让随机数发生器为我的电话号码打印0748,0023,0005等数字的附加0?谢谢!

import java.util.Random;
public class PhoneNumbers
{

public static void main (String[] args)
    {

    int digit1, digit2, digit3, digit4, digit5, digit6, digit7, digit8, digit9, digit10;

    Random generator = new Random();
    //creates a random number
    digit1 = generator.nextInt(8);
    digit2 = generator.nextInt(8);
    digit3 = generator.nextInt(8);
    digit4 = generator.nextInt(8); 
    digit5 = generator.nextInt(5);
    digit6 = generator.nextInt(3);
    digit7 = generator.nextInt(10);
    digit8 = generator.nextInt(10);
    digit9 = generator.nextInt(10);
    digit10 = generator.nextInt(10);

    //outputs the number including dashes
    System.out.println("A random 10-digit phone number:");
    System.out.print(digit1);
    System.out.print(digit2);
    System.out.print(digit3);
    System.out.print("-");
    System.out.print(digit4);
    System.out.print(digit5);
    System.out.print(digit6);
    System.out.print("-");
    System.out.print(digit7);
    System.out.print(digit8);
    System.out.print(digit9);
    System.out.print(digit10);

    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用前导零创建一个字符串:

int value = 7;
String valueStr = ("0000" + value);
valueStr = valueStr.substring(valueStr.length()-4);

然后只需打印字符串。

您还可以使用格式化程序:

int value = 7;
DecimalFormat myFormatter = new DecimalFormat("0000");
String output = myFormatter.format(value);

然后打印字符串

答案 1 :(得分:0)

Random generator = new Random();

// creates a random number
int part1 = generator.nextInt(1000);
int part2 = generator.nextInt(1000);
int part3 = generator.nextInt(10000);

// outputs the number including dashes
System.out.println("A random 10-digit phone number:");
System.out.printf("%03d-%03d-%04d\n", part1, part2, part3);

使用printf可以控制数字的格式。 %d是每个整数的占位符。 03中的%03d格式化最少3位数的数字,根据需要用0填充它。有关Format String Syntax格式化工作原理的详细信息,请参阅printf