将变量嵌入字符串中

时间:2013-07-09 12:44:40

标签: java string variables text

我想在字符串中使用变量,但我不知道如何。

这是我的代码:

private AbstractAction tester = new AbstractAction("test love match") {
    @Override
    public void actionPerformed(ActionEvent arg0) {
        match.setText("text \n text (VARIABLE) text \n text");  // <--  
    }
};

4 个答案:

答案 0 :(得分:1)

您可以尝试使用String.format,尤其是如果您想在单个字符串中以这种方式使用多个变量:

match.setText(String.format("text \n text %s text \n text", variable));

答案 1 :(得分:1)

喜欢这个?

match.setText("text \n text "  + yourText + " text \n text");

如果要使用资源中的String,可以这样做:

String yourText = res.getString(R.string.nameofyourtext);
match.setText(yourText);

这样,您可以在strings.xml(res / values / strings.xml)中更轻松地编辑和管理字符串

答案 2 :(得分:0)

您可以使用全局变量:

private String variable = "your text here";
private AbstractAction tester = new AbstractAction("test love match") {

        @Override
        public void actionPerformed(ActionEvent arg0) {


            match.setText("text \n text " + variable + " text \n text");

            }
    };

我希望它对你有所帮助。

答案 3 :(得分:0)

您要找的是连接运算符“+”

Java代码:

"Hello, " + name + "."

如果String name包含“Dave”,则此Java代码将提供String:

“你好,戴夫。”

[在Java中,我们不讨论变量,我们谈论对象。 ]