Java string format condition
conditional-statements, format, java, string
Solution
How about
return String.format("I met %s, "+(isMale?"he":"she")+" was OK.", name);
or
return String.format("I met %s, %s was OK.", name, (isMale ? "he" : "she"));
If you can change type of `isMale` to integer which for instance would represent mapping
- `0`->`she`,
- `1`->`he`
you could use MessageFormat and its `{id,choce,optionValue}`
static String createSentence(String name, int isMale) {
return MessageFormat.format("I met {0}, {1,choice,0#she|1#he} is fine",
name, isMale);
}
Problem
I want to write a sentence that is dependent on person's gender, here is what i could do: ``` String createSentence(String name, boolean isMale) { return String.format(isMale ? "I met %s, he was OK." : "I met %s, she was OK.", name); } ``` but you already see the fail in that (it works, but code is duplicit), i want something like: ``` String createSentence(String name, boolean isMale) { return String.format("I met %s, %b?'he':'she' was OK.", name, isMale); } ``` This ofc doesn't work, but is something like this possible? EDIT: Since I will want many sentences to be generated, even in different languages, and they will be stored is some sort or array, thus this solution is unhandy: ``` static String createSentence(String name, boolean isMale) { return String.format("I met %s, "+(isMale?"he":"she")+" was OK.", name); } ```