Dart

9.1 Dart Command-Line Tutorial: Add Two Numbers from User Input

In this small Dart project, you will build a simple command-line program that takes two numbers as input from the user, adds them together, and prints the result. This project demonstrates basic Dart syntax, user input handling, type conversion, and arithmetic operations.

✅ Project Overview

  • Command-line program built using Dart.
  • Prompt user for input using stdin.readLineSync().
  • Convert input strings to integers.
  • Perform arithmetic addition.
  • Print the result to the console.

✅ Dart Program Example

import 'dart:io';

void main() {
  // Prompt for the first number
  stdout.write('Enter the first number: ');
  String? input1 = stdin.readLineSync();

  // Prompt for the second number
  stdout.write('Enter the second number: ');
  String? input2 = stdin.readLineSync();

  // Validate input and convert to integers
  if (input1 == null || input2 == null) {
    print('Invalid input. Please enter numbers.');
    return;
  }

  int? number1 = int.tryParse(input1);
  int? number2 = int.tryParse(input2);

  if (number1 == null || number2 == null) {
    print('Invalid numbers entered. Please enter valid integers.');
    return;
  }

  // Add the numbers
  int sum = number1 + number2;

  // Display the result
  print('The sum of $number1 and $number2 is $sum');
}

Notes: Always validate user input in real-world applications. Here we assume the user enters valid integers.

✅ How It Works

  • stdin.readLineSync() reads a line of input from the user.
  • int.parse() converts the string input into an integer.
  • Arithmetic addition is performed using the + operator.
  • Result is printed using print() with string interpolation.

✅ Best Practices

  • Check for null or invalid inputs before parsing.
  • Use descriptive variable names like number1 and number2.
  • Keep the program simple and readable for beginners.
  • Use comments to explain each step for clarity.

✅ Exercises / Deliverables

  • Run the Dart program from the terminal and add two numbers.
  • Try modifying the program to subtract, multiply, or divide two numbers.
  • Extend the program to handle decimal numbers using double.parse().

Congratulations! Completing this simple Dart project demonstrates your ability to handle **user input**, perform **arithmetic operations**, and build a basic **command-line application** in Dart.

Leave a Reply

Your email address will not be published. Required fields are marked *