Why is "while((String tmp=x))" not valid Java syntax?
java, syntax
Solution
JLS §14.12:
WhileStatement:
while ( Expression ) Statement
JLS §15.27
Expression:
AssignmentExpression
JLS §15.26
AssignmentExpression:
ConditionalExpression
Assignment
Assignment:
LeftHandSide AssignmentOperator AssignmentExpression
LeftHandSide:
ExpressionName
FieldAccess
ArrayAccess
`LeftHandSide` cannot be a declaration, so it is not allowed.
Problem
I have a clarification about some Java code: What's the difference between these codes, that one can be compiled while the other cannot. I'm not interested on "how to fix the error" because I've already solved it, but more on an explanation about the problem: Working ``` public void x(){ HashMap<String , Integer> count= new HashMap<String, Integer>(); Scanner scan= new Scanner("hdsh"); String tmp; while((tmp=scan.next())!=null){ if(count.containsKey(tmp)){ count.put(tmp, 1); } else{ count.put(tmp, count.get(tmp)+1); } tmp=scan.next(); } } ``` Not Working ``` public void x(){ HashMap<String , Integer> count= new HashMap<String, Integer>(); Scanner scan= new Scanner("hdsh"); while((String tmp=scan.next())!=null){ if(count.containsKey(tmp)){ count.put(tmp, 1); } else{ count.put(tmp, count.get(tmp)+1); } tmp=scan.next(); } } ``` The errors of Eclipse are: Multiple markers at this line: - String cannot be resolved to a variable - Syntax error on token "tmp", delete this token - String cannot be resolved to a variable - Syntax error on token "tmp", delete this token