Data Types and Variables Practical Tasks

Hello all,
Could you please help me with the following task.
I can’t figure out how to write the constraints in the code: 1000 <= N <= 9999

Sum Digits
Write a program that reads a four-digit number and displays the sum of its digits
1213 => 1 + 2 + 1 + 3 = 7
2346 => 2 + 3 + 4 + 6 = 15
Input
On the first line, you will receive the four-digit number N
Output
On the only line of output, print the sum of digits
Constraints
1000 <= N <= 9999
Input
2346
Output
15

My solution so far is below. On intelliJ IDEa it sums any 4 digits, but when I submit as a solution in the academy’s prep platform it doesn’t accept it. I believe it is because of the constraints.

package com.company;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    Scanner user_input = new Scanner(System.in);
    System.out.println("Enter 4 digit number");


    int N = user_input.nextInt();
    int sum = 0;
    int rem = 0;

    while(N > 0) {
        rem = N % 10;
        sum = sum + rem;
        N = N / 10;
    }
    System.out.println("Sum of Digits =" + sum);

}

}

Hi,
you should not include System.out.println(“Enter 4 digit number”);
and also “Sum of Digits =” but just print the sum.

As someone else said previously - unfortunately, the judge system does not give you extra credit for politeness :grin:

Good luck :slight_smile:

2 Likes

Thank you so much! That solved it.
Such a simple difference though.

1 Like