Reputation: 13
I am currently trying to find out the sum of digits in a number. However, I am experiencing problems when I display the sum as it still shows all the previous sums, not just the final sum of digits only that I want.
int rem = 0, sum = 0, input = 0;
Scanner k = new Scanner(System.in);
System.out.println("Enter a number");
input = k.nextInt();
while (input > 0){
rem = input % 10;
sum = sum + rem;
input = input / 10;
System.out.println(sum);
}
This is part of my program above. So for example, when I input the number 25, the program outputs the number 5 first then 7. I understand why it inputs the number 5 as it is the remainder when divided by 10 and since I initialised sum = 0 at the start, the first sum will come out as 5 since sum = 0 + 5. However, I only want the final digit sum to be displayed.
How should I approach this problem? Any tips and advice would be greatly appreciated.
Upvotes: 1
Views: 640
Reputation: 71
As others said, the issue is that you print out the value of the sum variable inside your while loop. Either you change your code to:
while (input > 0) {
sum += input % 10;
input /= 10;
}
System.out.println(sum);
or you can use streams:
public static void main(String[] args) {
//1. Step: Read the number
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
Integer input = scanner.nextInt();
scanner.close();
//2. Step: calculate the sum with streams
int sum = String.valueOf(input).chars().map(Character::getNumericValue).sum();
//3. Step: Print out the result
System.out.println(sum);
}
Essentially what happens in the second step is this: We convert the integer into a string, we get the characters of the string and we call for each character using the map call the getNumericValue method to convert the character back to an integer, then we call the sum method to calculate the sum of these integers.
Upvotes: 0
Reputation: 11
Just print the result of the summation after the while loop. You find the every summation result of the number is because you print the result in your while loop. You should do as follows:
while (input > 0){
rem = input % 10;
sum = sum + rem;
input = input / 10;
}
System.out.println(sum);
if your input is 25, then it will show the summation as 7.
Upvotes: 0
Reputation: 54148
The while loop
is the thing that compute the sum, so you need to print the result after the computing :
while (input > 0){
rem = input % 10;
sum = sum + rem; //same as : sum += rem
input = input / 10; //same as : input /= 10;
}
System.out.println(sum);
Next to that, whith some tricks, and remove rem
variable, this is equivalent :
while (input > 0) {
sum += input % 10; //sum +=rem; --> sum += (input%10);
input /= 10;
}
System.out.println(sum);
Upvotes: 1