40

私はJavaが初めてで、Pythonから来ました。Python では、次のように文字列の書式設定を行います。

>>> x = 4
>>> y = 5
>>> print("{0} + {1} = {2}".format(x, y, x + y))
4 + 5 = 9
>>> print("{} {}".format(x,y))
4 5

Javaで同じことを複製するにはどうすればよいですか?

4

6 に答える 6

63

クラスはあなたが求めているもののMessageFormatように見えます。

System.out.println(MessageFormat.format("{0} + {1} = {2}", x, y, x + y));
于 2013-07-08T22:52:32.997 に答える
12

Java には、これと同様に機能 するString.formatメソッドがあります。これを使用する方法の例を次に示します。 これは、これらすべてのオプションが何であるかを説明するドキュメント リファレンスです。%

そして、ここにインラインの例があります:

package com.sandbox;

public class Sandbox {

    public static void main(String[] args) {
        System.out.println(String.format("It is %d oclock", 5));
    }        
}

これは「It is 5 oclock」と出力します。

于 2013-07-08T22:46:09.023 に答える
6

Slf4j には、Python と同様に、引数番号なしで受け入れるMessageFormatter.format()があります。{}Slf4j は一般的なロギング フレームワークですが、MessageFormatter を使用するためのロギングに Slf4j を使用する必要はありません。

于 2019-08-04T16:37:30.890 に答える
1

これを行うことができます(String.formatを使用)

int x = 4;
int y = 5;

String res = String.format("%d + %d = %d", x, y, x+y);
System.out.println(res); // prints "4 + 5 = 9"

res = String.format("%d %d", x, y);
System.out.println(res); // prints "4 5"
于 2013-07-08T22:50:35.330 に答える
0

Log4j 2( log4j-api) を使用する場合は、 を使用できますParameterizedMessage

ParameterizedMessage.format("{} {}", new Object[] {x, y});

また

new ParameterizedMessage("{} {}", x, y).getFormattedMessage(); // there is trimming
于 2022-01-04T07:16:53.620 に答える