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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started