2013年12月19日星期四

Ternary operator issues

String[] strs = new String[]{"", null, "1", "a", "1   ", "a  ", "   1", "    a"};

String str;

for (int i = 0; i < strs.length; i++) {
str = "92=" + strs[i] == null ? "" : strs[i] + "|";
System.out.println(i + "\t[" + str + "]");
}


After execution , the previous " 92 =" how no ?
------ Solution ----------------------- ---------------------
str = "92=" + strs[i] == null ? "" : strs[i] + "|";
changed
str = "92=" + (strs[i] == null ? "" : strs[i]) + "|";

------ Solution ------------------------------------- -------
because the ternary operator : ? precedence than the binary + operator is low, add operations to run , so in fact the above formula is equal to:
str = (("92 =" + strs [i]) == null) "":? strs [i] + "|";
first computing the sum + , and then determine whether the string is equal to the sum of the null.

landlord does want to express :
str = "92 =" + ((strs [i] == null) "":? strs [ i] + "|");

so enclosed on the first run ternary operator.

没有评论:

发表评论