简体   繁体   中英

Can someone explain what this Java code does?

I study Java as a subject in college and I got this code in the sheet to get the output, I executed the code to get the result of (11).

int i;  
for (i=1; i<10; i+=2);
System.out.println(i);

But what does it really do?

Let's start at the beginning, declare a variable named i of type int .

int i; 

Now we shall loop, initialize i to the value 1 , while i is less than 10 add 2 to i (1, 3, 5, 7, 9, 11). 11 is not less than 10 so stop looping.

for (i=1; i<10; i+=2); 

Finally, print i (11).

System.out.println(i);

Someone is being sneaky. Here's how it would lay out indented norrmally:

int i; 
for (i=1; i<10; i+=2)
    ; 
System.out.println(i);

int i; declares a variable named i of type int .

for (i=1; i<10; i+=2)
    ; 

is a for loop that starts by setting i to 1 , and then loops while i is less than 10, adding 2 to i` each time. The semicolon after the for is a no-op, an empty statement.

Try this version and see what happens:

int i; 
for (i=1; i<10; i+=2)
    System.out.println(i); 
System.out.println(i);

The code could be written more clearly like this (I will include comments denoting what each section does):

//declare a number variable
int i;

//this is a for loop
//the first part sets i to 1 to begin with
//the last part adds 2 to i each time
//and the middle part tells it how many times to execute
//in this case until i is no longer less than 10
for (i = 1; i < 10; i+=2);

//this prints out the final value, which is 11
System.out.println(i);

So your code will start i at 1 and then loop i = 3, i = 5, etc. until i is no longer less than 10 which happens when i = 9, i = 11 Then the program stops and you print the final value of i

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