java - why is it working fine with count++; but not with count = count++; -


this question has answer here:

i rookie in programming world , appreciate if can solve problem , make me understand.the output "no data entered".

public class trial {  public static void main(string[] args){     scanner firstno = new scanner(system.in);     int count = 0;     double sum = 0;     system.out.print("enter first number: ");     double firstnoin = firstno.nextdouble();     while (firstnoin != 0){          sum += firstnoin;          count = count++;          system.out.print("enter next number, or 0 end: ");          firstnoin = firstno.nextdouble();      }     if(count == 0){         system.out.println("no data entered.");     }     else {         system.out.println("average of data is: "+(sum/count)+", number of terms "+ count);     }             } } 

you have made semantic error - when program still compiles , works, doesn't work how wanted or doesn't expected to.

in case, have following:

count = count++  

if count = 0, piece of count keep count = 0. hence why getting 'no data entered' every time.

instead need:

count++; 

this increment count 1 each time.

alternatively, can use:

count = count + 1; 

again, take count's value , add 1 , save new value of count.

you can change + 2, + 3 , on , forth wish , can do:

count += 1 

which increment count 1 , can changed 2, 3 , on wish.


Comments