Search code examples
javamethodstype-conversiondereference

How to sum 3 digits of an integer?


I have been assigned to create a method that will take the users 3 digit input and add each separate value together (123 = 1 + 2 + 3 = 6). I have gotten stuck when my Professor would not allow us to convert the int to a string or we would lose points. I have attempted to use the x.charAt(); method but I am being told an int cannot be dereferenced.

public class Lab01
{

   private int sumTheDigits(int num)
   {
      char one = num.charAt(0);
      char two = num.charAt(1);
      char three = num.charAt(2);


      return one + two + three;
   }

   public static void main(String[] args)
   {
      Scanner input = new Scanner(System.in); 

      Lab01 lab = new Lab01();
      System.out.println("Enter a three digit number");
      int theNum = input.nextInt();
      int theSum = lab.sumTheDigits(theNum);



   }

}

Solution

  • It is not necessary convert the number to string, use the % operator to get the separate digits of an integer.

    something like this:

    private int sumTheDigits(int num){
    
        int sum = 0;
    
        while (num > 0) {
            sum += num % 10;
            num = num / 10;
        }     
    
        return sum;
    
    }