I have a Java question

Asked 2 years ago, Updated 2 years ago, 26 views

It's a question Try to print from 1 to 10 using i under the condition of the while statement. And add an if statement to output only multiples of 2

It's the code I coded.

public static void main(String[] args){
    int i = 1;
    while(i<11){
            if(i%2==0){
                System.out.println(i);
      }
            i++; 
    }
  }
}

What I'm curious about is why does the i++ have to come out to print? If you're inside, you can't print anything out. It's very complicated ㅠ<

java

2022-09-22 22:11

1 Answers

i++; Command

if(i%2==0){
System.out.println(i);
i++;
}

If you are in an if statement in this way, i increases only when the conditions are met. Since the first value of i is 1, the condition that i%2 is 0 is definitely false The contents within the conditional statement are not executed.

So I'm not increasing, and I'm not going to get 2 so nothing's going to be output.


2022-09-22 22:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.