Welcome Guest.

1Answers

Consult a java program, the code is given, why is the running result like this. If the statement inside will make the value of a affect the next one?

Asked by: Henry Hughes 252 views IT October 13, 2018

public class Else {   

    public static void main(String[] args) {       

    // TODO Auto-generated method stub

        int a=0;

        if(a++==1)

            System.out.println ("a==1");

        else

            System.out.println("a!=1");

        if(++a==2)

            System.out.println("a==2");

        else

            if(a*a>5)

                 System.out.println("a>5");

     &Nbsp;      else

                System.out.println(" a<5");

        if(a<5)

        {

            if(++a>=3)

             {

                System.out.println(" a>=3");

            }

            if(++a-3==0)

            {

                System.out.println("a==0");

             }

        }

     }

}

Run results:

a!=1

a==2

a>=3

1 Answers

  1. +3Votes  

    Result Analysis

      if(a++==1) //a is post-++, the value of the expression is 0, so it does not hold

    output

               System.out.println("a!=1"); //a!=1

    A=1 at this time

    and

           if(++a==2)

    Because it is the former ++, the expression and the value of a 2, the condition is established

    output System.out.println("a==2"); //a==2

    and the following is not executed after else until

     if(a<5)

    At this point, a==2, so the condition is true

     continue if(++a> =3)

    is ++ first, so the expression and the value of a are 3, the condition is true, and the output is

    System.out.println("a>=3" ); //a>=3

    final judgment

     if(++a-3==0)

    is again ++, So a=4, the value of the expression is 4-3=1, which is not true.

    This is the main assessment

    1. The difference between ++ and ++

    2.if the order of judgment

    Question: I always thought that the value after the if judgment would not affect another if. I thought that when the second if, the a is still the original 0 and then ++a.

    Susan- October 13, 2018 |