(Sum the digits in an integer ) Write a method that computes the sum of the digi
ID: 3685176 • Letter: #
Question
(Sum the digits in an integer ) Write a method that computes the sum of the digits in an integer . Use the following method header: public static int sumDigits(long n) For example, sumDigits(234) returns 9 (2 + 3 + 4). (Hint: Use the % opera- tor to extract digits, and the / operator to remove the extracted digit. For instance, to extract 4 from 234, use 234 % 10 (= 4). To remove 4 from 234, use 234 / 10 (= 23). Use a loop to repeatedly extract and remove the digit until all the digits are extracted. Write a test program that prompts the user to enter an integer and displays the sum of all its digits. My code is working but it gives the wrong answer for longer inputs such as: Enter·an·integer:57657577899
Here is the code that I am using:
import java.util.Scanner;
public class SumDigits {
public static int sumDigits(long n){
int num,remainder = 0, sum = 0;
num=(int) n;
while(num != 0){
remainder = num % 10;
num = num /10;
sum = sum + remainder;
}
return sum;
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer:");
long num=input.nextLong();
int result = sumDigits(num);
System.out.println("The sum of the digits in "+ num +" is "+ result);
}
}
Explanation / Answer
Java Program to Calculate the sum of digits
package org.students;
import java.util.Scanner;
public class SumDigits {
public static int sumDigits(long n){
int remainder = 0, sum = 0;
long num;
num=n;
while(num != 0){
remainder = (int) (num % 10);// we have to use type cast operator here to convert from long type to int type.
num = num /10;
sum = sum + remainder;
}
return sum;
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer:");
long num=input.nextLong();
int result = sumDigits(num);
System.out.println("The sum of the digits in "+ num +" is "+ result);
}
}
------------------------------------------------------------------------------------------------------------------------
output:
Enter an integer:57657577899
The sum of the digits in 57657577899 is 75
_______________________________________________________________________________
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.