Results 1 to 4 of 4
Thread: Homework Help
 04032012, 06:44 PM #1Member
 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; }
 04032012, 08:07 PM #2Senior Member
 Join Date
 Feb 2012
 Posts
 117
 Rep Power
 0
Re: Homework Help
What does
Java Code:int temp = (int)Math.abs(n);
 04042012, 07:07 AM #3Member
 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;
 04102012, 07:11 PM #4Member
 Join Date
 Apr 2012
 Posts
 3
 Rep Power
 0
Similar Threads

Need some help with my homework.
By JacobM in forum New To JavaReplies: 11Last Post: 02042011, 02:42 AM 
Homework help
By lackingunderstanding4now in forum New To JavaReplies: 4Last Post: 11082010, 03:18 AM 
Homework help
By noobster in forum New To JavaReplies: 13Last Post: 10312010, 09:02 PM 
Need help with homework.
By JavaNewbie0000 in forum New To JavaReplies: 2Last Post: 07312008, 03:06 PM
Bookmarks