Lesson 37: Console Applications Part 1

Learn how to create and develop console applications in Visual Basic 2022

Key Takeaway

Console applications provide a lightweight, text-based interface ideal for learning programming fundamentals and creating command-line utilities.

In Visual Basic 2022, console applications run in a command-line interface without a graphical user interface. They are perfect for:

Learning Fundamentals

Master programming concepts without UI distractions

Command-line Tools

Create utilities for automation and scripting

Server Applications

Build background services and daemons

Rapid Prototyping

Quickly test ideas and algorithms

37.1 Creating a Console Project

To create a new console application in Visual Studio 2022:

  1. Launch Visual Studio 2022
  2. Select "Create a new project"
  3. Search for "Console App" and select "Console App (.NET Framework)"
  4. Name your project and choose a location
  5. Click "Create"
Console Application project selection

Figure 37.1: Creating a new console application project

37.2 Console I/O Fundamentals

Console applications primarily use these methods for input and output:

Method Description Example
Console.Write() Outputs text without a newline Console.Write("Enter name: ")
Console.WriteLine() Outputs text with a newline Console.WriteLine("Hello World")
Console.ReadLine() Reads a line of text input Dim name = Console.ReadLine()
Console.ReadKey() Reads a single key press Console.ReadKey(True)
BasicConsole.vb
Module Module1
    Sub Main()
        ' Display a welcome message
        Console.WriteLine("=== Welcome to VB2022 Console ===")
        Console.WriteLine()
        
        ' Get user input
        Console.Write("Please enter your name: ")
        Dim userName As String = Console.ReadLine()
        
        ' Display personalized message
        Console.WriteLine($"Hello, {userName}! Welcome to console programming.")
        Console.WriteLine()
        
        ' Wait for key press before exiting
        Console.WriteLine("Press any key to exit...")
        Console.ReadKey(True)
    End Sub
End Module
=== Welcome to VB2022 Console ===
Please enter your name:
John
Hello, John! Welcome to console programming.
Press any key to exit...

37.3 Simple Calculator

This example demonstrates a basic calculator with arithmetic operations:

Calculator.vb
Module Calculator
    Sub Main()
        Console.WriteLine("===== SIMPLE CALCULATOR =====")
        Console.WriteLine()
        
        ' Get first number
        Console.Write("Enter first number: ")
        Dim num1 As Double = Console.ReadLine()
        
        ' Get second number
        Console.Write("Enter second number: ")
        Dim num2 As Double = Console.ReadLine()
        
        ' Perform calculations
        Console.WriteLine()
        Console.WriteLine("RESULTS:")
        Console.WriteLine($"{num1} + {num2} = {num1 + num2}")
        Console.WriteLine($"{num1} - {num2} = {num1 - num2}")
        Console.WriteLine($"{num1} * {num2} = {num1 * num2}")
        
        ' Check for division by zero
        If num2 <> 0 Then
            Console.WriteLine($"{num1} / {num2} = {num1 / num2}")
        Else
            Console.WriteLine("Cannot divide by zero!")
        End If
        
        Console.WriteLine()
        Console.WriteLine("Press Enter to exit...")
        Console.ReadLine()
    End Sub
End Module
===== SIMPLE CALCULATOR =====
Enter first number:
25
Enter second number:
5
RESULTS:
25 + 5 = 30
25 - 5 = 20
25 * 5 = 125
25 / 5 = 5
Press Enter to exit...

37.4 Number Guessing Game

A classic number guessing game that demonstrates loops and conditional logic:

GuessingGame.vb
Module GuessingGame
    Sub Main()
        ' Initialize random number generator
        Dim rand As New Random()
        Dim secretNumber As Integer = rand.Next(1, 101)
        Dim guess As Integer
        Dim attempts As Integer = 0
        
        Console.WriteLine("=== NUMBER GUESSING GAME ===")
        Console.WriteLine("I'm thinking of a number between 1 and 100.")
        Console.WriteLine()
        
        ' Game loop
        Do
            Console.Write("Enter your guess: ")
            
            ' Validate input
            If Not Integer.TryParse(Console.ReadLine(), guess) Then
                Console.WriteLine("Please enter a valid number!")
                Continue Do
            End If
            
            attempts += 1
            
            ' Check guess
            If guess < secretNumber Then
                Console.WriteLine("Too low! Try again.")
            ElseIf guess > secretNumber Then
                Console.WriteLine("Too high! Try again.")
            Else
                Console.WriteLine()
                Console.WriteLine($"Correct! You guessed it in {attempts} attempts.")
            End If
        Loop Until guess = secretNumber
        
        Console.WriteLine("Thanks for playing!")
        Console.ReadLine()
    End Sub
End Module
=== NUMBER GUESSING GAME ===
I'm thinking of a number between 1 and 100.
Enter your guess:
50
Too low! Try again.
Enter your guess:
75
Too high! Try again.
Enter your guess:
60
Too high! Try again.
Enter your guess:
55
Too low! Try again.
Enter your guess:
57
Correct! You guessed it in 5 attempts.
Thanks for playing!

37.5 File Processing

This example demonstrates reading and writing files in a console application:

FileProcessor.vb
Imports System.IO

Module FileProcessor
    Sub Main()
        Console.WriteLine("=== FILE PROCESSING DEMO ===")
        Console.WriteLine()
        
        ' Create a new file
        Dim filePath As String = "sample.txt"
        
        Console.WriteLine("Writing to file...")
        File.WriteAllText(filePath, "Hello, VB2022 Console!" & Environment.NewLine)
        File.AppendAllText(filePath, "This is a second line." & Environment.NewLine)
        
        Console.WriteLine("File created successfully.")
        Console.WriteLine()
        
        ' Read and display file content
        Console.WriteLine("Reading file content:")
        Console.WriteLine("----------------------")
        
        Dim fileContent As String = File.ReadAllText(filePath)
        Console.WriteLine(fileContent)
        
        Console.WriteLine()
        Console.WriteLine("Press Enter to exit...")
        Console.ReadLine()
    End Sub
End Module
=== FILE PROCESSING DEMO ===
Writing to file...
File created successfully.
Reading file content:
----------------------
Hello, VB2022 Console!
This is a second line.
Press Enter to exit...

Console Application Summary

Key concepts for console applications in VB2022:

Concept Description Key Methods
Input/Output Communicating with the user Write, WriteLine, ReadLine, ReadKey
Control Flow Managing program execution If, Select Case, For, Do While
Data Types Storing and manipulating data Integer, String, Double, Boolean
File I/O Reading and writing files File.ReadAllText, File.WriteAllText

Entry Point

All console applications start execution in the Sub Main() method

Simplicity

Console apps are lightweight and ideal for learning core programming concepts

Practicality

Great for creating command-line tools, scripts, and utilities

Practical Exercises

Apply your console application knowledge with these hands-on exercises:

Exercise 1: Temperature Converter

Create a program that converts between Celsius and Fahrenheit. The user should choose the conversion direction.

Exercise 2: Multiplication Table Generator

Generate a multiplication table for a given number (from 1 to 10) and display it in a formatted way.

Exercise 3: Simple ATM Simulator

Create an ATM simulation with options to check balance, deposit, and withdraw funds.

Exercise 4: Text File Analyzer

Create a program that reads a text file and reports the number of lines, words, and characters.

Exercise 5: Password Generator

Generate random passwords based on user-specified length and complexity requirements.

Challenge Exercise: Contact Manager

Develop a console-based contact manager that can add, list, search, and save contacts to a file.

Next Lesson

Learn advanced console techniques in Lesson 38: Console Applications Part 2.

Related Resources

VB6 Tutorial

Mastering VB6 Programming

Explore Tutorials

Visual Basic Examples

Practical VB code samples for real-world applications

View Examples

Excel VBA Tutorial

Learn how to automate Excel by creating VBA macros

Learn More