Android Android Java

Average of Two Numbers in Android Studio5 min read

Calculating the average of two numbers in Android Studio is a simple task that can be achieved by following these steps.

Average of Two Numbers in Android Studio
Average of Two Numbers in Android Studio

Here is an example of how you can calculate the average of two numbers in Android Studio




Step 1: Create a new Android Studio project and choose “Empty Activity” as the activity template.

Step 2: In the layout file (e.g. activity_main.xml), add two EditText views and a Button view. The EditText views will be used to input the numbers and the Button will be used to trigger the average calculation. You can also add a TextView view to display the result.

XML:

Step 3: In the activity class (e.g. MainActivity.java), define two variables to store the input numbers and a third variable to store the result.

Step 4: In the onCreate method, set up the Button click listener and implement the average calculation logic. To get the input numbers from the EditText views, you can use the getText method and convert the text to a number using the parseInt or parseDouble method.

Output:

Average of Two Numbers in Android Studio
Average of Two Numbers in Android Studio

Additional: To make the user interface more user-friendly, you can add error handling to handle cases where the user does not enter a valid number in the EditText views. You can do this by using the try and catch blocks to catch any exceptions that may be thrown when parsing the input to a number.

To text exception you must change inputType property as text in XML.

You can also add additional functionality to the app, such as the ability to clear the input and result, or to perform other mathematical operations such as subtraction, multiplication, and division.

MainActivity.java

Youtube:

Leave a Comment