> Java code? why is the hw site saying this is wrong!?

Java code? why is the hw site saying this is wrong!?

Posted at: 2014-12-18 
This Should work

1> You forgot to add } at the end to close class and

2> Also use public class className for when using packages.

import java.util.Scanner;

class SumDigits

{

public static int sumDigits(long n)

{

int i=10;

int sum=0;

while (n!=0)

{

sum+=n%10;

n=n/10;

}

return sum;

}

public static void main(String[] args)

{

System.out.print("Enter an integer:");

Scanner stdin = new Scanner(System.in);

long z = stdin.nextLong();

System.out.print("The sum of the digits in " + z + " is " + sumDigits(z));

} }

Looks fine to me, at least for non-negative numbers.

Was there something in the fine print or lecture notes about requirements? I'd use println instead of print on the final output, and maybe take an absolute value on n, but everything else looks golden.

By the way, practice sites are nice...but I think that homework bots for assessed assignments is an atrocity.

You don't need the line:

int i=10;

Remove it. it is unnecessary. Apart from that, its perfect. Worked for me.

6.2) (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:

import java.util.Scanner;

public class SumDigits

{

public static int sumDigits(long n)

{

int i=10;

int sum=0;

while (n!=0)

{

sum+=n%10;

n=n/10;

}

return sum;

}

public static void main(String[] args)

{

System.out.print("Enter an integer:");

Scanner stdin = new Scanner(System.in);

long z = stdin.nextLong();

System.out.print("The sum of the digits in " + z + " is " + sumDigits(z));

}

}