• Post Reply Bookmark Topic Watch Topic
  • New Topic

dynamic argument in System.out.format(string,argument)  RSS feed

 
Niklas Karlsson
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
i whant to do a DYNAMIC argument in
System.out.format(string,argument);
or something similar..

the problem
I have a dynamic text thar can look like this:

System.out.format(" %c , %c %n", item[0],item[1]);

and then i can have :

System.out.format(" %c , %c , %c , %c , %c %n", item[0],item[1], item[1],item[0],item[1]);

i cant do like this unfortnatly:
String argument = "item[0],item[1], item[1],item[0],item[1]";
and
string info = " %c , %c , %c , %c , %c %n";
and then :
System.out.format(info,argument);

does any have an ide'a?
:-(
 
Gordon Brown
Ranch Hand
Posts: 58
2
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about making your item array of type Object[], and then simply pass that as the second parameter, rather than passing each of the array items individually?
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you mean you have an array which needs to be printed out?

You can set up a loop to add the same number of %cs as there are elements in the array. But there are bound to be more object‑oriented ways to do it.
You can use Arrays#toString.
You can create a Stream from some arrays (won't work in Java7):-
Arrays.stream(myCharArray).forEach(c -> System.out.printf("%c ", c));
System.out.println();

That might not work with a char[]; look in the Arrays class.

And other people will doubtless be able to think of other solutions.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use a StringJoiner for each element in an array. You can turn the array into a String and remove characters like comma and square bracket.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!