Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

Thread: Why is it summing a long negative integer to zero????

1. Why is it summing a long negative integer to zero????

```import java.util.Scanner;
public class Exercise2_6M
{
public static void main(String[] args)
{
// Create a Scanner
Scanner input = new Scanner(System.in);

// Enter amount
System.out.print("Enter an integer:");
int integer = input.nextInt();

// Calculations
int rinteger = Math. abs (integer);
int sum = 0;
int i=0;

//loop through each digit (starting from the least significant) until the end of the number
while(rinteger / Math.pow(10,i) > 0)
{
sum+=getDigit(rinteger,i);
i++;
}

// Display results
System.out.println("Sum all digits in " + integer + " is " + sum);
}

public static int getDigit(int num, int power)
{
return (num % (int)Math.pow(10,power+1)) / (int)Math.pow(10,power);
}
}```

2. Re: Why is it summing a long negative integer to zero????

Is this program built to find the sum of the digits? Or to find the sum of the digits up to the number?

Would 123 be... 1+2+3
or
Would 123 be... 1+2+3+4+5...+122+123

3. Re: Why is it summing a long negative integer to zero????

As far as i know, when you apply the power function, it crosses the limit of integer. And shows you the result after that.
You must take care of memory sizes provided to different data types.