Ответ 1
Try:
String formatted = String.format(str, args.toArray());
Это дает:
Entered number = 1 and string = abcd
Рассмотрим строку.
String Str = "Entered number = %d and string = %s"
Скажем, у меня есть список объектов
List<Objects> args = new ArrayList<Objects>();
args.add(1);
args.add("abcd");
Есть ли способ, в котором я могу заменить эти args на Str, так что я получаю строку типа "Entered number = 1 and string = abcd "
?
Обобщая это, я планировал сбрасывать все вопросы и аргументы в файле (например, json) и выполнять их во время выполнения. Пожалуйста, дайте мне знать, если есть лучшие способы сделать это.
Try:
String formatted = String.format(str, args.toArray());
Это дает:
Entered number = 1 and string = abcd
Вы можете использовать следующее:
String str = "Entered number = %d and string = %s";
List<Object> args = new ArrayList<Object>();
args.add(1);
args.add("abcd");
System.out.println(String.format(str, args.toArray()));
даст результат:
Entered number = 1 and string = abcd
От JLS 8.4.1 Параметры формата:
The last formal parameter in a list is special;
it may be a variable arity parameter, indicated by an
elipsis following the type.
If the last formal parameter is a variable arity parameter of type T,
it is considered to define a formal parameter of type T[].
The method is then a variable arity method. Otherwise, it is a fixed arity
method. Invocations of a variable arity method may contain more actual
argument expressions than formal parameters. All the actual argument
expressions that do not correspond to the formal parameters preceding
the variable arity parameter will be evaluated and the results stored
into an array that will be passed to the method invocation.
Смотрите этот вопрос на fooobar.com/questions/461167/...!
final String myString = String.format(Str, 1, "abcd");
Используйте соответствующие переменные