Josh Gager Josh Gager - 5 months ago 9
Java Question

How to format a string like #.#.#.#

I am new to Java so sorry if this is an easy problem. I am trying to generate a random IP address. I am generating the 4 numbers individually and want to format them like #.#.#.#

My code is as follows:

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


I am getting the error


too many arguments for format string (found:4, expected:0)


What am I doing wrong?

Answer

I think you just need a range and assign it to your string (without much fuzz):

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