📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Introduction
Kotlin is a modern, expressive, and concise programming language that runs on the Java Virtual Machine (JVM). It offers a plethora of features that make coding fun and efficient. In this blog post, we will explore a simple Kotlin program that adds two numbers provided by the user.
2. Program Overview
This program will do the following:
1. Prompt the user to enter two numbers.
2. Read the numbers from the user.
3. Add the two numbers.
4. Display the result.
3. Code Program
import java.util.Scanner fun main() { // Creating an instance of the Scanner class to take input from the user val reader = Scanner(System.in) // Prompting the user to enter the first number print("Enter the first number: ") // Reading the first number val num1 = reader.nextDouble() // Prompting the user to enter the second number print("Enter the second number: ") // Reading the second number val num2 = reader.nextDouble() // Adding the two numbers val sum = num1 + num2 // Displaying the result println("The sum of $num1 and $num2 is: $sum") }
Output:
Enter the first number: 5.5 Enter the second number: 6.5 The sum of 5.5 and 6.5 is: 12.0
4. Step By Step Explanation
1. Import Statement: At the beginning of our program, we imported the Scanner class from the java.util package. This class helps us to read input from the user.
2. Scanner Initialization: We created an instance of the Scanner class named 'reader'. This will allow us to get inputs from the user.
3. Reading First Number: We used the print function to prompt the user to enter the first number. The reader.nextDouble() function then reads this number and stores it in the num1 variable.
4. Reading Second Number: Similarly, we prompted the user to enter the second number and stored it in the num2 variable.
5. Calculation: We added the values of num1 and num2 and stored the result in the sum variable.
6. Output: Finally, we used the println function to display the sum of the two numbers.
With this simple program, we showcased the power and simplicity of Kotlin for basic operations. It provides a glimpse into how user input can be handled and how arithmetic operations can be performed with ease.
Comments
Post a Comment
Leave Comment