sum of digits till the sum is one-digit number

your code maybe loop forever

the right solution is the following below

public static void main(String[] args) throws ParseException {
int y = 777;// if y is 777 i am getting blank
int sum = 0;
String s;
char[] ch;
do {
    sum = 0;
    s = String.valueOf(y);
    ch = s.toCharArray();
    if (ch.length > 1) {
        for (int i = 0; i < ch.length; i++) {
            sum += Character.getNumericValue(ch[i]);
        }
    } else {
        System.out.println(ch[0]);
        break;
    }
    y = sum;
} while (ch.length > 1);
}

Maybe the better choice is the following code

public static void main(String[] args) throws ParseException {
    int y = 333;// if y is 777 i am getting blank
    int sum = 0;
    while (y % 10 != 0) {
        sum += y %10;
        y = y / 10;
        if (0 == y && sum >= 10) {
            y = sum;
            sum = 0;
        }
    }
    System.out.println(sum);
}

hope that helped


For a task like this, it is best practise to use recursion.

The workflow in pseudocode would look like this:

procedure sumTillOneDigit(n)
    split n into it's digits
    s := sum of all digits of n

    if s has more than one digit:
        sumTillOneDigit(s)
    else
        output s

I am intentionally writing this in pseudocode, since this should help you solving the task. I will not give you a Java implementation, as it looks like a homework to me.

For more information see:

  • https://en.wikipedia.org/wiki/Recursion_(computer_science)
  • http://introcs.cs.princeton.edu/java/23recursion/

You are getting that because you put the print statement in else condition..

Also note that to reset your sum value before reusing it. I.e. Set sum=0 at the start of do loop.

EDIT : there are two solutions to print you value 1. Don't put you print statements inside else conditions

  1. Print sum outside the do while loop

Tags:

Java

Do While