Nested suggestion of choice in MessageFormat?

I am trying to make simple logic using java.text.MessageFormat:

MessageFormat cf = new MessageFormat( "{0,choice, 1<hello|5<{1,choice,1<more than one|4<more than four}}"); Object[] array = {3, 1}; System.out.println(cf.format(array)); 

With the words: if the first parameter is more than 1, print โ€œhelloโ€ if it is more than 5 than if the second parameter is more than 1, print โ€œmore than oneโ€ if the second parameter is more than 4 prints โ€œmore than fourโ€.

I did not find anyone who said that this is impossible, but I get an IllegalArgumentException:

Choice Pattern incorrect: 1<hello|5<{1,choice,1<more than one|4<more than four}

Is there any way to do this? Thanks!

Whole stack:

 Exception in thread "main" java.lang.IllegalArgumentException: Choice Pattern incorrect: 1<hello|5<{1,choice,1<more than one|4<more than four} at java.text.MessageFormat.makeFormat(Unknown Source) at java.text.MessageFormat.applyPattern(Unknown Source) at java.text.MessageFormat.<init>(Unknown Source) at test.Test5.main(Test5.java:18) Caused by: java.lang.IllegalArgumentException at java.text.ChoiceFormat.applyPattern(Unknown Source) at java.text.ChoiceFormat.<init>(Unknown Source) ... 4 more 
+6
source share
1 answer

If you write such a template, ChoiceFormat cannot parse the format because it cannot know if the control characters, such as the format delimiter ( | ), are for the internal format or external format. But if you specify a nested format, you can tell the parser that the quoted text does not contain any control characters that it should parse. ChoiceFormat then simply return text containing another ChoiceFormat template.

If the MessageFormat class MessageFormat a ChoiceFormat , it again parses the result as a MessageFormat to handle additional parameter processing, which then processes the internal ChoiceFormat .

Thus, the code works if you write the template as follows:

 MessageFormat cf = new MessageFormat( "{0,choice, 1<hello|5<'{1,choice,1<more than one|4<more than four}'}"); Object[] array = {3, 1}; System.out.println(cf.format(array)); 
+8
source

All Articles