Search code examples
javadigit

Digit Adder In Java Not Working


Examples of my output:

123 output: 5

111 output: 2

Lots work but ones like the above don't add correctly... Can anyone point me in the right direction? Here is my code:

import java.util.Scanner;

public class DigitAdder {

public static void main(String [] args) {
    int input;
    int output = 0;

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter a positive integer: ");
    input = scan.nextInt();

    if(input < 0) {
        System.out.println("Enter a positive integer: ");
        return;
    }

    while(input > 1) {
        output = output + (input % 10);
        input /= 10;
    }

    System.out.println(output);

}

}

Solution

  • Looks like you're not counting the first digit when your input starts with 1.

    Try :

    while(input >= 1) {
        output = output + (input % 10);
        input /= 10;
    }