简体   繁体   中英

Could someone explain what is wrong with this java code?

for (i = 0; i < 10; i++) {
    int sum;

    sum = sum+i;
}

System.out.println("Sum is " + sum);

I'm trying to figure out what is wrong with this piece of code that is supposed to run in java. In VSCode im getting a lot of errors when trying to compile and run it, but I can't seem to understand what is causing the errors.

sum is defined inside the loop, it's only available in that scope.

And i variable is not declared, it can be declared just in the loop.

This is a way to fix it:

int sum = 0;

for (int i = 0; i < 10; i++) {
    sum = sum + i; // or sum += i;
}

System.out.println("Sum is " + sum);

sum is declared inside for loop. It's scope end inside the loop and you are trying to access it outside the for loop and hence the compiler will throw error.

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