【问题标题】:How to replace a string with another string and insert it into the next line of code in Java如何用另一个字符串替换一个字符串并将其插入到Java中的下一行代码中
【发布时间】:2013-01-08 17:02:21
【问题描述】:

我不知道如何在程序运行时用字符串替换字符串。 这甚至可能吗? 在程序运行时,我想用另一个词替换一个词,然后从该行继续运行。

我怎么能这样做? 谢谢大家

hstring.replace("picstart", "up1");
g.drawPixmap(Assets.picstart , 128, 160);

【问题讨论】:

  • 你需要用变量替换常量。
  • 您不能在运行时修改自己的源代码。你到底想做什么?您可能需要使用反射。
  • 您可以使用反射按名称查找字段,但这并不是一个好主意。

标签: java string replace


【解决方案1】:

不要使用反射。假设您的资产代码处理您的图像、纹理或任何情况:

String hstring = "picstart";
// ... stuff happens
// that forces us to change hstring! ...
hstring = hstring.replace("up1"); // or you could just say hstring = "up1";
g.drawPixmap(Assets.getAssetFor(hstring), 128, 160);

然后在您的静态资产类中,您可以拥有:

public PixelMap getAssetFor(String identifier) {
     if (identifier.equals("picstart") {
         return new PicStartPixelMap();
     }
     else if (identifier.equals("up1")) {
         return new UpOnePixelMap();
     }
}

【讨论】:

  • 我要试试 getassetfor(hstring),也许可以做到
  • @WilliamMChildsIv 您必须自己编写该功能。我不是在谈论任何预先构建的方法。
  • 为什么要 hstring 这样工作?>>>> g.drawPixmap(Assets.hstring , 128, 160);
  • 您需要提供更多信息吗? Assets.hstring 是字符串吗? drawPixMap 是一个函数吗? hstring 是设置还是为空? hstring 是否有正确的 String 值?
  • 在资产类中>>public static Pixmap>Assets.picstart = g.newPixmap("picstart.png", PixmapFormat.ARGB4444);在类中我打电话给 >>g.drawPixmap(Assets.hstring , 128, 160);但 hstring 是一个字符串,但在资产类中是个疯子
【解决方案2】:

您的代码看起来像这样。

if (condition) {
    g.drawPixmap(Assets.picstart , 128, 160);
} else {
    g.drawPixmap(Assets.up1 , 128, 160);
}

【讨论】:

    【解决方案3】:

    String 是不可变的,这意味着您必须将结果分配给变量:

    hstring = hstring.replace(...);
    

    【讨论】:

    • 感谢您的投票。现在,是否有可能知道投反对票的原因是什么?
    猜你喜欢
    • 2021-06-15
    • 2012-09-25
    • 2021-11-16
    • 2015-02-11
    • 2013-12-03
    • 1970-01-01
    • 2012-08-14
    • 2012-09-11
    相关资源
    最近更新 更多