Question: Please help me in this problem. Essentially, the problem asks me to calculate the sum of all integers for an inputted integer. My work is
Please help me in this problem. Essentially, the problem asks me to calculate the sum of all integers for an inputted integer. My work is fine on that aspect, however, the maximum I can calculate is for a 3-digit integer. Please help me rewrite my code to compute the sum of an integer of any length. PLEASE KINDLY FOLLOW MY CODE STRICTLY WITHOUT CHANGING IT ENTIRELY.
import java.util.*; public class Exercise06_02 { public static void main(String[] args) { // Create a scanner class Scanner input = new Scanner(System.in); // Prompt the user to enter the two integers System.out.println("Please enter an integer from 1 to 999 to calculate the sum of the digits: "); int inputtedInter = input.nextInt(); // Display the output System.out.println("The sum of all digits of the integer is " + sumDigits(inputtedInter) + "."); } /* Declare the method */ public static int sumDigits(long n) { long lastDigit = n % 10; long nextNumberGroup_1 = n / 10; long nextDigit_1= nextNumberGroup_1 % 10; long firstDigit = nextNumberGroup_1 / 10; long result = lastDigit + nextDigit_1 + firstDigit; return (int)result; } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
