I have a variable of type Hashmap<String,Integer>.
In this, the Integer value might have to go some manipulation depending upon the value of a flag variable. I did it like this...
Hashmapvariable.put( somestring,
if (flag_variable) {
//manipulation code goes here
new Integer(manipulated value);
} else {
new Integer(non-manipulated value);
}
);
But I get an error:
Syntax error on token(s), misplaced constructs.
at the Hashmapvariable.put call.
I also get another error
Syntax error on token ")", delete this token.
at the final ");" line. But I can't delete the ")" - its the closing parentheses for the put method call.
I don't get this. What mistake am I doing?
-
You cannot place a statement in the method call.
However, one option could be to make an method that returns a
Integersuch as:private Integer getIntegerDependingOnFlag(boolean flag) { if (flag) return new Integer(MANIPULATED_VALUE); else return new Integer(NON-MANIPULATED_VALUE); }Then, you can make a call like this:
hashmap.put(someString, getIntegerDependingOnFlag(flag)); -
new Integer(flag_variable ? manipulated value : non-manipulated value)Does the trick
Edit: On Java 5, I suppose you can also write
hashmap.put(someString, flag_variable ? manipulated value : non-manipulated value)due to auto-boxing.
Tom Hawtin - tackline : If the alternate expressions are not both of type int then the semantics become "interesting". -
This isn't scheme, so if statements don't evaluate to a value. You'll have to use a tri-if-thing (the name escapes me for some reason right now) or create a function, as someone else said.
PhiLho : Name: it is a ternary operator, or more precisely, a comparison operator (there could be other kinds of ternary operators, although I haven't seen them in popular languages...).
0 comments:
Post a Comment