简体   繁体   中英

If statement not working even after fulfilling condition

This is a solution to a problem of finding sum of even digits of number. Main

public class Main {
    public static void main(String[] args) {
        int mySum=EvenDigitSum.getEvenDigitSum(879);
        System.out.println(mySum);
    }
}

Above in main Method.

Even DigitSum
public class EvenDigitSum {
    public static int getEvenDigitSum(int number){
       int sum=0;
        if (number<0){
            return -1;
        }else {
            while (number>0){
                int lastDigit=(number%10);
                System.out.println("last digit"+lastDigit);
                if (lastDigit%2==0){
                    sum=(sum+lastDigit);
                    System.out.println("my sum"+sum);
                }
                number/=10;
            }
            return sum;
        }
    }
}

here I have got 2 print statements one in while loop and other in if statement. The one in while loop gives correct output but one in if statement never gives one. In main method my number is 879 which has 8 so for 8 if statement should work but it is not working.My final sum of even digits is coming 0.

got mistake used / instead of %

In this line:

if (lastDigit / 2 == 0)

You're checking if half of the last digit is 0. Of course, this will only happen if the digit is 0 or 1. Instead, use % 2 to get the remainder:

if (lastDigit % 2 == 0)

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