如何格式化字符串,如#。#。#。#。

时间:2016-06-13 00:52:44

标签: java random string.format

我是Java的新手,很抱歉,如果这是一个简单的问题。我想生成一个随机的IP地址。我正在单独生成4个数字,并希望将它们格式化为#。#。#。#

我的代码如下:

static final Random _random = new Random(Integer.parseInt(seed) / 2);

String ip = String.format(
    Locale.US,
    "#.#.#.#",
    _random.nextInt((254 - 1) + 1) + 1,
    _random.nextInt((254) + 1),
    _random.nextInt((254) + 1),
    _random.nextInt((254 - 1) + 1) + 1
);

我收到错误

  

格式字符串的参数太多(找到:4,预期:0)

我做错了什么?

2 个答案:

答案 0 :(得分:3)

我认为你只需要一个范围并将其分配给你的字符串(没有太多的模糊):

final Random random = new Random();
final String ip = String.format("%d.%d.%d.%d", random.nextInt(255) + 1,
    random.nextInt(256), random.nextInt(256), random.nextInt(255) + 1);
//System.out.printf("%s%n", ip);

答案 1 :(得分:2)

您可以使用上述方法,也可以使用#clan格式,DecimalFormat

Random random = new Random();
DecimalFormat format = new DecimalFormat("###");
String value = new StringBuilder()
        .append(format.format(random.nextInt(256))).append(".")
        .append(format.format(random.nextInt(256))).append(".")
        .append(format.format(random.nextInt(256))).append(".")
        .append(format.format(random.nextInt(256))).toString();
相关问题