Java Data Type Exercises: Adds all the digits in the integer between 0 and 1000
Java Data Type: Exercise-3 with Solution
Write a Java program that reads an integer between 0 and 1000 and adds all the digits in the integer.
An integer is a number that can be written without a fractional component. For example, 23, 6, 0, and −1245 are integers, while 3.25, 7 1⁄2, and √3 are not.
Test Data
Input an integer between 0 and 1000: 565
Sample Solution:
Java Code:
import java.util.Scanner;
public class Main {
public static void main(String[] Strings) {
Scanner input = new Scanner(System.in);
System.out.print("Input an integer between 0 and 1000: ");
int num = input.nextInt();
int firstDigit = num % 10;
int remainingNumber = num / 10;
int SecondDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int thirdDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int fourthDigit = remainingNumber % 10;
int sum = thirdDigit + SecondDigit + firstDigit + fourthDigit;
System.out.println("The sum of all digits in " + num + " is " + sum);
}
}
Sample Output:
Input an integer between 0 and 1000: 565 The sum of all digits in 565 is 16
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program that reads a number in inches, converts it to meters
Next: Write a Java program to convert minutes into a number of years and days.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework