00:01
In this video, we will write a program that reads an integer between 0 and 1 ,000 and adds all the digits in the integer.
00:07
For example, if our number was 932, the sum of the digits would be 14.
00:14
We can use the modulist operator to extract the 1s digit.
00:20
We can also use the integer division operator to remove the 1s digit.
00:27
If we're using these both the 10, so mod 10 would get us the one digit and integer divide by 10 would truncate the one digit.
00:40
So we can go ahead and import java .util .scanner, since we know we'll be taking user input.
00:59
Next, we can go into our main method and we can create a new scanner object, call it.
01:05
Input and we can use system .in a predefined object as an argument because this represents the standard input stream.
01:20
The next thing we're going to want to do is to prompt the user to enter a number between 0 and 1000.
01:32
To do this, we can use system .out .print .l .n.
01:51
The next thing we're going to want to do is store.
01:54
This and we can call it number equals input.
01:59
Nextinth, which is a method of the scanner class that ensures our input is being stored as an integer.
02:23
Next, we're going to want to create another integer.
02:27
We'll call it n and we can set this to number.
02:30
We're going to create another integer n since we'll be creating a while loop.
02:36
Now you could, because the question is, asks for an integer between 0 and 1 ,000, you could take any number and calculate the ones, tens, and hundreds digits, and then sum those.
02:51
But i think for practice, it's better to use a while loop because this would be applicable to any number, any bigger number, and it kind of explains what's happening along the way.
03:03
So we can do int sum because in our while loop, we're going to want to calculate the sum.
03:09
We'll need some starting to start.
03:10
At zero so we can add to this.
03:12
We'll create our while loop and our condition will be when n is greater than zero because every time we enter the while loop we're going to end up removing a digit so eventually our n will go to zero.
03:30
Now it's important that we don't use number in case we want to use the number at the end of the program maybe we want it for something else.
03:41
It's important to realize which numbers you're going to be editing within a loop, et cetera.
03:50
So i suppose our input is 932.
03:55
932 is greater than zero.
03:57
So we're going to enter the y loop, and we're going to want to take off the one's digit two.
04:04
So we can do that by doing n mod 10, but we're going to want to add it to some, so we can do that by doing sum plus equals n mod 10.
04:12
And this is the same as sum equals sum plus n on 10...