# Thread: Homework Help

1. Member
Join Date
Apr 2012
Posts
3
Rep Power
0

## Homework Help

Hello everyone,
I'm having issues with one of my programs and need some help. The purpose of the program is to summarize digits into an int using a method. My code works for positive numbers however, when I input a negative number, the result is positive. I've tried several if statements but cannot seem to get it working. Any suggestions? Here is my code:

Java Code:
```public class Ex5_2SumDigit {
public static void main(String[] args) {

String integerString;
int integer;
integerString = JOptionPane.showInputDialog("Please enter an integer: ");
integer = Integer.parseInt(integerString);

JOptionPane.showMessageDialog (null, "The sum of digits for " + integer +
" is " + sumDigits(integer));
}

public static int sumDigits(long n) {
int temp = (int)Math.abs(n);
int sum = 0;

while (temp != 0) {
int remainder = temp % 10;
sum += remainder;
temp = temp / 10;

}

return sum;
}```

2. Senior Member
Join Date
Feb 2012
Posts
117
Rep Power
0

## Re: Homework Help

What does
Java Code:
`int temp = (int)Math.abs(n);`
do to negative numbers?

3. Member
Join Date
Apr 2012
Location
Texas USA
Posts
2
Rep Power
0

## Re: Homework Help

Its because of the abs() method your code is not working for negative numbers try the following code for SumDigits()
public static int sumDigits(long n) {
int temp = (int)(n);
int sum = 0;

while (temp != 0) {
int remainder = temp % 10;
sum += remainder;
temp = temp / 10;

}

return sum;

4. Member
Join Date
Apr 2012
Posts
3
Rep Power
0

## Re: Homework Help

I got my program to work, I was simply just overlooking a very simple mistake. I'm not sure why I put Math.abs there in the first place. Thanks for the help.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•