Kotlin Input and Output Tutorial: Reading User Input, Printing Output, Formatting, and Mini Projects
This Kotlin Input and Output tutorial explains how to read user input from the console, print output, and format output effectively in Kotlin programs. The chapter also includes hands-on mini projects such as a calculator, number guessing game, student marks calculator, and temperature converter. Each topic is explained with clear examples and best practices to help beginners build confidence through practical coding.
Kotlin Input and Output – Complete Tutorial
Reading User Input
In Kotlin, user input is typically read from the standard input using readLine().
Example: Reading a String
Reading and Converting Input
Since readLine() returns a nullable String, conversion is required for numbers.
Safe Input Handling
Best Practices
- Always handle null values from
readLine(). - Use
toIntOrNull()to avoid runtime exceptions. - Validate user input wherever possible.
Printing Output
Kotlin provides simple functions to display output.
println
Prints output and moves to a new line.
Prints output without a new line.
Best Practices
- Use
printfor prompts. - Use
printlnfor results and logs.
Output Formatting
Kotlin supports string templates for clean output formatting.
String Templates
Formatting with Decimal Precision
Best Practices
- Prefer string templates over string concatenation.
- Use formatting for financial or measurement values.
Mini Projects (With Examples)
Mini Project 1: Calculator
Objective
Create a simple calculator that performs basic arithmetic operations.
Code Example
Best Practices
- Validate operators.
- Handle division by zero.
Mini Project 2: Number Guessing Game
Objective
User guesses a predefined number.
Code Example
Best Practices
- Use loops for repeated attempts.
- Give hints for better user experience.
Mini Project 3: Student Marks Calculator
Objective
Calculate total and average marks.
Code Example
Best Practices
- Validate input range.
- Format output clearly.
Mini Project 4: Temperature Converter
Objective
Convert Celsius to Fahrenheit.
Code Example
Best Practices
- Use meaningful variable names.
- Display formatted output.
Summary
This chapter covered reading user input, printing and formatting output in Kotlin, followed by practical mini projects that strengthen understanding of basic syntax, control flow, and functions. These projects form a strong foundation for moving toward object-oriented programming and real-world applications.