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:
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();
}
}
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();
}
}
Multiple markers at this line:
You cannot declare a variable inside of an expression. (except for the first part of a for
loop)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With