简体   繁体   中英

What is wrong in declaring data type of variable inside while loop but not inside for loop?

If I declare variable then initialize variable inside while loop, there is no problem.

int a; 
while((a=someValue)!= -1)`

But if I declare variable and initialize it inside while loop, there is problem in compile time.

while ((int a=someValue) != -1)

What is the reason for this? Declaring and initializing variable seems to be fine in For Loop though.

Full Code snippet:

correct one

int a;
while ((a=Integer.parseInt(reader.nextLine())) != -1) {
    sum.addNumber(a);
}
System.out.println("sum: "+sum.sum());

wrong one

while ((int a=Integer.parseInt(reader.nextLine())) != -1) {
        sum.addNumber(a);
    }
System.out.println("sum: "+sum.sum());

Because you can only write an expression inside the parenthesis of a while loop. Semantically, this makes sense: suppose you declare a variable inside while() , then on each iteration it will create a new local variable, and you can't declare a local variable more than once.

Second will already give a syntax error. Unlike For loop, you cannot declare a variable in a While loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM