Skip to content
Advertisement

Assigning a TextComponent object differently based on try catch

I’m trying to take a String kd and either assign it to a TextComponent object, or if the string can be parsed into a Double value then assign it to a TextComponent using a DecimalFormat object.

I check for known strings and do it this way, like this:

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)));
}

but i want to catch all non-double-parsable strings to be handled at once.

I can’t do this because kd would get assigned twice when string cannot be parsed:

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);
}

What is the most compact way to achieve my goal here?

Advertisement

Answer

You know I guess writing it out here helped me see what the issue seems to have been.

When using an if block, the TextComponent needs to be final and null beforehand, but not with try / catch.

I just removed the final and now it compiles, though I haven’t tested the plugin again yet.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement