Reputation: 3042
While converting a mathematical formula to Java, I encountered square brackets (I found them in the formula). I don't know what they mean in mathematics, because I'm no math expert, just a 14-year old hobby-programmer (so I've not reached to these "difficulty-levels" in math in school).
It's obvious that I can't write something like this:
double x = [5 / 2] * (3 + 5 * 2);
because [
and ]
are used for arrays.
Therefore, I wonder what to replace them with in order to make Java accept it and interpret it correctly.
Upvotes: 0
Views: 5385
Reputation: 1015
Square brackets can replaced by parenthesis. I assume you're aware about BODMAS used for mathematics problem resolution, hence brackets are used for separation and prioritizing operators .
double x = (5 / 2) * (3 + 5 * 2);
System.out.println(x);
double y = 5 / 2 * 3 + 5 * 2;
System.out.println(y);
above code snippet gives output:-
26.0
16.0
Upvotes: 0
Reputation: 19168
You can remove those square brackets and replace them with normal parentheses ()
.
double x = (5 / 2) * (3 + 5 * 2);
Based on the priority, the first statement to be evaluated will be the square-bracket statement because of highest-precedence
and left-to-right associativity
in solving this particular expression.
Upvotes: 4