Saturday, 15 August 2015

How can I sum the second digit to the last digit in an integer on java? -



How can I sum the second digit to the last digit in an integer on java? -

can tell me how can prepare programme create "sumsectolastd" operator following: 1- sum sec digit lastly digit in integer (for example: 324 + 564 + 9876 = 29 since (2 + 4) + (6 + 4) + (8 + 7 + 6) = 29). 2- if insert 1 digit only, still able give me sum ( example: 1 + 3 + 4 = 8).

class="snippet-code-js lang-js prettyprint-override">import java.util.*; public class pr66{ public static void main(string[] args){ scanner scan = new scanner (system.in); int num1; int num2; int num3; int sumlastd; int sumsectolastd; system.out.print("please write integer: "); num1 = scan.nextint(); system.out.print("please write integer: "); num2 = scan.nextint(); system.out.print("please write integer: "); num3 = scan.nextint(); sumlastd = num1 % 10 + num2 % 10 + num3 % 10; system.out.println(); system.out.println("- lastdigitsum: " + num1 % 10 + " + " + num2 % 10 + " + " + num3 % 10 + " = " + sumlastd); if (sumlastd % 2 == 0) system.out.println("- lastdigitsum: integer"); else system.out.println("- lastdigitsum: odd integer"); system.out.println(); sumsectolastd = (num1/10) % 10 + (num2/10) % 10 + (num3/10) % 10; system.out.println("- sectolastsum: " + (num1/10) % 10 + " + " + (num2/10) % 10 + " + " + (num3/10) % 10 + " = " + sumsectolastd); if (sumsectolastd % 2 == 0) system.out.println("- sectolastsum: integer"); else system.out.println("- sectolastsum: odd integer"); }//main }//pr66

this sums lastly digits:

sumlastd = num1 % 10 + num2 % 10 + num3 % 10;

to sum of lastly , sec last, add together result of above calculation sec lastly digits:

sumsectolastd = (num1/10) % 10 + (num2/10) % 10 + (num3/10) % 10 + sumlastd;

to create work single digit numbers require additional checks, , create code much bigger:

sumlastd = (string.valueof(num1).length() > 1 ? num1 % 10 : num1) + (string.valueof(num2).length() > 1 ? num2 % 10 : num2) + (string.valueof(num3).length() > 1 ? num3 % 10 : num3);

yes, can set onto multiple lines, compiler ignores unnecessary whitespace.

for sumsectolastd modify above to:

sumsectolastd = (string.valueof(num1).length() > 2 ? (num1/10) % 10 : num1) + (string.valueof(num2).length() > 2 ? (num2/10) % 10 : num2) + (string.valueof(num3).length() > 2 ? (num3/10) % 10 : num3) + sumlastd;

java sum

No comments:

Post a Comment