【问题标题】:Assigning a TextComponent object differently based on try catch基于 try catch 以不同方式分配 TextComponent 对象
【发布时间】:2021-07-11 23:29:05
【问题描述】:

我正在尝试获取字符串 kd 并将其分配给 TextComponent 对象,或者如果字符串可以解析为 Double 值,则使用 DecimalFormat 对象将其分配给 TextComponent .

我检查已知字符串并这样做,如下所示:

final TextComponent kd;
if (PlayerMeta.getStats(target).kd.contains("!") || PlayerMeta.getStats(target).kd.contains("null")) {
    kd = new TextComponent("K/D: " + PlayerMeta.getStats(target).kd);
} else {
    kd = new TextComponent("K/D: " + new DecimalFormat("#.###").format(Double.parseDouble(PlayerMeta.getStats(target).kd)));
}

但我想立即捕获所有不可双重解析的字符串。

我不能这样做,因为当字符串无法解析时,kd 会被分配两次:

final TextComponent kd;
try {
    kd = new TextComponent("K/D: " + new DecimalFormat("#.###").format(Double.parseDouble(PlayerMeta.getStats(target).kd)));
} catch (NumberFormatException e) {
    kd = new TextComponent("K/D: " + PlayerMeta.getStats(target).kd);
}

在这里实现我的目标最紧凑的方法是什么?

【问题讨论】:

    标签: java try-catch variable-assignment bukkit


    【解决方案1】:

    你知道我想把它写在这里帮助我了解问题似乎是什么。

    使用 if 块时,TextComponent 需要预先为 final 和 null,但 不是 与 try / catch。

    我刚刚删除了final,现在它可以编译了,虽然我还没有再次测试这个插件。

    【讨论】:

      猜你喜欢
      • 2021-11-25
      • 2012-12-22
      • 2023-01-16
      • 2016-02-14
      • 2012-04-25
      • 2012-05-14
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多