As explained in the previous tutorial, the number variables are useful for making calculations. In today's example we will create a simple app that adds two numbers. This will cover:
1. How to convert a string to a number variable
2. How to add 2 numbers and the logic behind it
I will start by creating a new project. In my layout, I have 2 edittexts where a user enters a number and then a Textview to display the answer. It will therefore look like this:
Fo us to do a calculation, we will need to start by converting the contents of our edittext to a number variable. Once it has been converted we can then use the green Operator blocks to calculate. So I will place the logic onTextChanged. The image below shows how to add an onTextChanged event
Once I've added my event, I will then create a number variable with the name "firstnumber" - you can give it any name that makes sense to you e.g. dailysales, subject1, score etc. Once you've created the variable, place the logic(blocks) to convert it to a string. Here is how it will look
Since we want the numbers to add up automatically when we enter the second digit, we will add the numbers on the second edittext's onTextChanged event. If you do not want to do this, you can add a button or place the logic where you want the addition to be triggered. I have created another number variable and given it the name "secondnumber". I have created an additional number variable called "answer" and this will be our total. In hindsight, I should have named it total, but I'm sure you get it. The logic for my second edittext will look like this:
That's it. We can now run our app and it will look like this
If you want to do additional or more complex calculations simply use the other available blocks... you can see some of them in the image below. Remember that you can place these blocks inside each other, as long as the shape fits.
Comments