I read today a little code with MessageFormat and Choice format class but my mind got a little confusion. I haven't enough understanding what's going on, and why in situation in this task in printStocks method.
I had IllegalArgumentException, I had to add one "null" to
Format[] testFormats = {null, null, dateFormat, fileform};
I added because I looked in help section. I suppose it's correlated with four elements in MessageFormat string:
MessageFormat pattform = new MessageFormat("{0} {1} | {5} {6}");
I suppose that {0} is related to "name", {1} to "symbol", {5} and {6} are correlated somehow with ChoiseFormat object which decide to use version from
String[] filepart = {"change {4}", "open {2} and last {3}"};
How to grasp and better understand connection and cooperation ChoiceFormat with MessageFormat? I feel that I need a little tiny "click" in my mind to grasp whole think.
public static void printStocks(List<Stock> stocks, Date actualDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
double[] filelimits = {0d, actualDate.getTime()};
String[] filepart = {"change {4}", "open {2} and last {3}"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
Format[] testFormats = {null, null, dateFormat, fileform};
MessageFormat pattform = new MessageFormat("{0} {1} | {5} {6}");
pattform.setFormats(testFormats);
for (Stock stock : stocks) {
String name = ((String) stock.get("name"));
String symbol = (String) stock.get("symbol");
double open = !stock.containsKey("open") ? 0 : ((double) stock.get("open"));
double last = !stock.containsKey("last") ? 0 : ((double) stock.get("last"));
double change = !stock.containsKey("change") ? 0 : ((double) stock.get("change"));
Date date = (Date) stock.get("date");
Object[] testArgs = {name, symbol, open, last, change, date, date.getTime()};
System.out.println(pattform.format(testArgs));
}
}
public static class Stock extends HashMap<String, Object> {
public Stock(String name, String symbol, double open, double last) {
put("name", name);
put("symbol", symbol);
put("open", open);
put("last", last);
put("date", getRandomDate(2020));
}
public Stock(String name, String symbol, double change, Date date) {
put("name", name);
put("symbol", symbol);
put("date", date);
put("change", change);
}
}