
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:
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;
}

Re: Homework Help
What does
Code:
int temp = (int)Math.abs(n);
do to negative numbers?

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;

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.