-1

Essentially I'm trying to create a program that counts up the sum of the digits of the number, but every time a number that is over 1000 pops up, the digits don't add up correctly. I can't use % or division or multiplication in this program which makes it really hard imo. Requirements are that if the user inputs any integer, n, then I will have to be able to compute the sum of that number.

I've already tried doing x>=1000, x>=10000, and so forth a multitude of times but I realized that there must be some sort of way to do it faster without having to do it manually.

import java.util.Scanner;

public class Bonus {
    public static void main(String[] args) {
        int x;
        int y=0;
        int u=0;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter the number:");
        x = s.nextInt();
        int sum = 0;
        {
            while(x >= 100) {
                x = x - 100;
                y = y + 1;
            }
            while(x>=10) { 
                x = x - 10;
                u = u + 1;
            }
            sum = y + u + x;
            System.out.println("The sum of the digits in your number is" + " " + sum);
        }
    }
}

So if I type in 1,000 it displays 10. And if I type in 100,000 it displays 100. Any help is appreciated

HuanG0
  • 11
  • 1
  • 1
    What exactly are the requirements here? You could convert it to a `String` and check the length? – GBlodgett May 16 '19 at 22:40
  • Possible duplicate of [Sum all the digits of a number Javascript](https://stackoverflow.com/questions/38334652/sum-all-the-digits-of-a-number-javascript) – PM 77-1 May 16 '19 at 22:44
  • @PM77-1 sadly not a dupe of that since it's Java, and % is not permitted. – Jason May 16 '19 at 22:48
  • @Jason: https://stackoverflow.com/questions/27096670/how-to-sum-digits-of-an-integer-in-java – PM 77-1 May 16 '19 at 23:04
  • @PM77-1 `I can't use % or division or multiplication in this program` – Jason May 17 '19 at 00:23

1 Answers1

0

Convert the number to a string, then iterate through each character in the string, adding its integer value to your sum.

int sum = 0;
x = s.nextInt();
for(char c : Integer.toString(x).toCharArray()) {
    sum += Character.getNumericValue(c);
}
Jason
  • 11,744
  • 3
  • 42
  • 46