Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "while((String tmp=x))" not valid Java syntax?

Tags:

java

syntax

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
like image 530
David H Avatar asked Aug 26 '12 20:08

David H


2 Answers

You cannot declare a variable inside of an expression. (except for the first part of a for loop)

like image 186
SLaks Avatar answered Sep 22 '22 21:09

SLaks


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.

like image 10
Jeffrey Avatar answered Sep 20 '22 21:09

Jeffrey