0

I know how the ++ operator and -- operator works.This is my code to count the no of digit in an integer and it works perfectly.

import java.util.Scanner;

public class modified_sepadigit
{
    public static void main(String args[])
    {
        Scanner input=new Scanner(System.in);
        System.out.println("Enter a  number");
        int no=input.nextInt();
        int noOfDigit=0;
        int tempNo=no;
        while(tempNo>=1)
        {
            tempNo=tempNo/10;
            noOfDigit++;
        }
        System.out.println("No of digits:"+ noOfDigit);


    }
}

But if i change noOfDigit++ in the while loop to noOfDigit=noOfDigit++, then i always get ouput as 0.
Now i know that it is meaningless to write noOfDigit=noOfDigit++ when i can simply write noOfDigit++
What i think is that If that statement worked then i should get input as the (total no of digits in an number) -1 beacause of the way post increment works.
Can  anybody tell me why i am getting output as 0 always if i change noOfDigit++ in the while loop to noOfDigit=noOfDigit++ ?  
3
Contributors
3
Replies
4
Views
4 Years
Discussion Span
Last Post by hszforu
Featured Replies
  • It prints out 0 because it takes noOfdigits, stores a copy then adds 1 and returns the copy. So you get the value of what it was, but also increments it at the same time. Therefore you print out the last value though it gets incremented. Read More

  • i=i++; is a no-op - it leaves i unchanged. What happens is: the current value of i is stored i is incremented the stored value is assigned to i See http://skeletoncoder.blogspot.fr/2006/09/java-tutorials-i-i.html Read More

1

It prints out 0 because it takes noOfdigits, stores a copy then adds 1 and returns the copy. So you get the value of what it was, but also increments it at the same time. Therefore you print out the last value though it gets incremented.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.