java - SumDigits using Parameter -
okay, created digitssum application. class digitssum , contain static method called sumdigits(i done this). ( didn't part) names must match these including capitalization, sumdigits method should take single parameter, integer, , return sum of digits in integer, sumdigits method should not print anything, , should return answer using return statement. can use main method test sumdigits method, , printing should happen there. know whether if did fine or no..also method return should if entered number, suppose 345, output should 3+4+5=12 --> 1+2 = 3. doing wrong here? in advanced!
import java.util.scanner; public class sumdigits { public static double sumdigits (int a){ int sum; int t= a%10; sum= t+t; = a/10; return (sum); } public static void main (string [] args){ double sumdigit; int integer; scanner in = new scanner(system.in); system.out.print("enter positive integer: "); integer = in.nextint(); sumdigit = sumdigits(integer); system.out.println ("the sum of digit is:" +sumdigit); } }
i believe you're missing few things:
- you should close streams , external resource in general. id est: closing
scanner
before leavingmain
method - as has been pointed out in comments, should use recursive method implement
sumdigits
, because reflects actual behavior you're trying implement.
your code this:
public class main { public static int sumdigits(final int a) { int sum = 0; int b = a; { sum += b % 10; b = b / 10; } while (b > 0); if (sum >= 10) { return sumdigits(sum); } return sum; } public static void main(final string[] args) { double sumdigit; int integer; try (final scanner in = new scanner(system.in)) { system.out.print("enter positive integer: "); integer = in.nextint(); sumdigit = sumdigits(integer); system.out.println("the sum of digit is: " + sumdigit); } } }
what did here in recursive method can decomposed in 2 parts:
- you calculate sum of digits of given number (done
do/while
loop) - if sum greater or equals 10, need return recursive application of
sumdigits
on value... otherwise, returnsum
.
note didn't change sumdigits
method main
one, closes scanner
using try-with-resource syntax.
Comments
Post a Comment