Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
837 views
in Technique[技术] by (71.8m points)

string - Java printf using variable field size?

I'm just trying to convert some C code over to Java and I'm having a little trouble with String.printf.

In C, to get a specific width based on a variable, I can use:

printf("Current index = %*d
", sz, index);

and it will format the integer to be a specific size based on sz.

Trying:

System.out.println(String.format("Current index = %*d
", sz, index));

results in an error since it doesn't like the *.

I currently have the following kludge:

System.out.println(String.format("Current index = %" + sz + "d
", index));

but I'm hoping there's a slightly better way, yes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Declare an extra variable before using printf:

String format = "%" + fieldSize + "d";
System.out.printf(format, yourVariables);

(this is the first solution I found from a web search)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...