如何格式化像#.#.#.#这样的字符串
How to format a string like #.#.#.#
我是 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
);
我遇到错误
too many arguments for format string (found:4, expected:0)
我做错了什么?
我认为您只需要一个范围并将其分配给您的字符串(没有太多模糊):
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);
可以使用上面提到的方法,或者#格式可以使用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();
我是 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
);
我遇到错误
too many arguments for format string (found:4, expected:0)
我做错了什么?
我认为您只需要一个范围并将其分配给您的字符串(没有太多模糊):
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);
可以使用上面提到的方法,或者#格式可以使用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();