views:

109

answers:

3

I am getting an compilation error "not a statement" for the below code. Not sure what's wrong. inMax is a hasmap. tcharge is a string and it's a key. Is this one a valid statement?

Double tMaxCharge= (Double)inMax.get(tCharge);
+5  A: 

looks fine, check the statement before that one.

objects
i have a if statement before if <condition>Double tMaxCharge= (Double)inMax.get(tCharge); else do somethingI just changed this statement to be enclosed in braces and it started workingif <condition> {Double tMaxCharge= (Double)inMax.get(tCharge); }else do somethingNot sure why it's working inside braces.
Arav
Because you are defining a local variable (tMaxCharge) it needs to be in a block. If you defined tMaxCharge before the if you would not need the braces.
objects
@objects: Just curious, what good is a Double declaration and initialization in a block with no other statements using it?
Phanindra K
no use at all :)
objects
Thanks a lot for the info
Arav
no worries, glad I could help
objects
+2  A: 

Java's compiler isn't always as helpful as it thinks. Look at other lines nearby where it points you. The problem may be on the line before.

I agree with objects' answer, but to avoid casting, can you just use generics in this case, eg:

HashMap<String,Double> myMap = new HashMap<String,Double>();

myMap.put("foo", 3.14); //or new Double(3.14)

myMap.get("foo") //evaluates to type Double (and can be autoboxed to a double)
Ellie P.
Thanks a lot for the info
Arav
+2  A: 

Apparently you code was something like:

if (someCondition)
    Double tMaxCharge= (Double)inMax.get(tCharge); 
else
    doSomething();

As @objects says, that is not valid Java syntax. A LocalVariableDeclarationStatement is a BlockStatement but not a Statement and an if statement requires a Statement following the ).

But if you think about it, a LocalVariableDeclarationStatement that it not inside a Block is pointless. The scope of the declaration would end immediately, so the declared identifier could not be used. (And it has to end immediately or you would get all sorts of linguistic anomalies.)

Stephen C
"then" in java ?
Jijoy
ooops ... fixed
Stephen C