If-satser och loopar

“I find your lack of logical flow… disturbing.” - Darth Vader (probably talking about bad if-statements)

Welcome back, tactical commander! Du har lärt dig The Force of Data, The Jedi Arts, och Building the Rebel Alliance. Nu är det dags för the critical skill every rebel leader behöver: decision making och repetitive actions. I en galax full av Imperial threats, måste du kunna make quick decisions och execute repeated maneuvers. Detta är your battlefield tactics training!

If-satser - The Art of Tactical Decisions

If-satser är som battle commands i real combat. Beroende på situationen (enemy position, shield status, ammunition levels) gör du olika tactical decisions. Precis som Admiral Ackbar inte bara blindly attackerar utan först checkar “Is it a trap?” - your kod måste också think before acting!

Enkel If-sats (Single Tactical Assessment)


int shieldStrength = 15;

if (shieldStrength < 20)
{
    Console.WriteLine("SHIELDS CRITICAL! Retreat immediately!");
    Console.WriteLine("This is not the time for heroics!");
}

Just like in space combat: Om shields är low, fall back! No questions asked.

If-else - Binary Tactical Choice (Attack or Defend)


int enemyShips = 12;
int rebelShips = 8;

if (rebelShips >= enemyShips)
{
    Console.WriteLine("We have the numbers! ATTACK!");
    Console.WriteLine("May the Force be with our pilots!");
}
else
{
    Console.WriteLine("We're outnumbered! Execute tactical retreat!");
    Console.WriteLine("Live to fight another day - that's the Rebel way!");
}

If-else if - Multiple Battle Scenarios (Complex Tactical Assessment)


int pilotSkill = 85;
int shipCondition = 75;
bool hasForceAbilities = false;

if (pilotSkill >= 90 && shipCondition >= 80)
{
    Console.WriteLine("Mission Assignment: Death Star Trench Run!");
    Console.WriteLine("You're our best pilot - this is it!");
}
else if (pilotSkill >= 80 && shipCondition >= 70)
{
    Console.WriteLine("Mission Assignment: TIE Fighter Escort Duty");
    Console.WriteLine("Keep those transports safe!");
}
else if (pilotSkill >= 70)
{
    Console.WriteLine("Mission Assignment: Patrol Duty");
    Console.WriteLine("Stay in formation and watch for Imperial scouts!");
}
else
{
    Console.WriteLine("Mission Assignment: Maintenance Duty");
    Console.WriteLine("Every rebel has a role - keep those ships running!");
}

// Special Force user bonus
if (hasForceAbilities)
{
    Console.WriteLine("SPECIAL ADDITION: Force-guided targeting available!");
    Console.WriteLine("Use the Force, Luke... I mean, pilot!");
}

Jämförelseoperatorer - The Battlefield Assessment Tools


int imperialTroops = 50;
int rebelTroops = 30;
int generalMoral = 85;

// Exact comparison (==) - för precise tactical requirements
if (imperialTroops == rebelTroops)
    Console.WriteLine("Even numbers! This will be interesting...");

// Not equal (!=) - för avoiding bad situations
if (rebelTroops != 0)
    Console.WriteLine("We still have fighters! The rebellion continues!");

// Greater than (>) - för advantage assessment
if (generalMoral > imperialTroops)
    Console.WriteLine("High morale vs low numbers - morale wins!");

// Less than (<) - för disadvantage recognition
if (rebelTroops < imperialTroops)
    Console.WriteLine("We're outnumbered but not outmatched!");

// Greater or equal (>=) - för minimum requirements
if (generalMoral >= 80)
    Console.WriteLine("Troops are ready for battle! High spirits detected!");

// Less or equal (<=) - för maximum acceptable risk
if (imperialTroops <= 100)
    Console.WriteLine("Enemy numbers manageable - proceeding with assault!");

Logiska operatorer - Complex Battle Conditions

AND (&&) - Multiple Requirements (ALL must be true)


int fuelLevel = 85;
int ammunitionLevel = 90;
bool pilotReady = true;
bool weatherClear = true;

if (fuelLevel > 80 && ammunitionLevel > 80 && pilotReady && weatherClear)
{
    Console.WriteLine("ALL SYSTEMS GO! Launching attack on Imperial base!");
    Console.WriteLine("Red Squadron, this is your moment!");
}
else
{
    Console.WriteLine("Mission scrubbed - not all conditions met");
    Console.WriteLine("We don't take unnecessary risks with pilot lives");
}

OR (||) - Alternative Conditions (ANY can be true)


string weatherCondition = "stormy";
bool hasStealthTech = false;
bool enemyDistracted = true;

if (weatherCondition == "clear" || hasStealthTech || enemyDistracted)
{
    Console.WriteLine("Conditions favorable for infiltration mission!");
    Console.WriteLine("Proceeding with stealth approach to Imperial facility");
}
else
{
    Console.WriteLine("Too risky for infiltration - waiting for better conditions");
}

NOT (!) - Avoiding Bad Conditions (Opposite check)


bool isImperialTrap = false;
bool isAckbarPresent = true;

if (!isImperialTrap && isAckbarPresent)
{
    Console.WriteLine("Admiral Ackbar confirms: It's NOT a trap!");
    Console.WriteLine("Proceeding with confidence!");
}
else if (isImperialTrap)
{
    Console.WriteLine("IT'S A TRAP! - Admiral Ackbar");
    Console.WriteLine("Abort mission immediately!");
}

For-loopar - Repetitive Military Operations

For-loopar används för precise, counted operations - som launching specific number of fighters eller checking multiple systems:


// Launch sequence för Red Squadron
Console.WriteLine("Initiating Red Squadron launch sequence...");

for (int pilotNumber = 1; pilotNumber <= 12; pilotNumber++)
{
    Console.WriteLine($"Red {pilotNumber}, you are cleared for takeoff!");
    Console.WriteLine($"  - Pilot callsign: Red {pilotNumber}");
    Console.WriteLine($"  - Ship status: Ready");

    if (pilotNumber == 5)
    {
        Console.WriteLine($"  - SPECIAL: Red Five has Force abilities - extra targeting!");
    }
}

Console.WriteLine("Red Squadron fully deployed! May the Force be with them!");

För-loop anatomy (Military precision):

  • int pilotNumber = 1 - Starting pilot count (Red 1)
  • pilotNumber <= 12 - Continue until all 12 fighters launched
  • pilotNumber++ - Move to next pilot (Red 2, Red 3, etc.)

Countdown Sequence (Imperial Doomsday Device style)


Console.WriteLine("Death Star main weapon charging...");

for (int countdown = 10; countdown >= 1; countdown--)
{
    Console.WriteLine($"Weapon charging: {countdown} seconds remaining");

    if (countdown == 5)
    {
        Console.WriteLine("WARNING: Final charging sequence initiated!");
    }
    else if (countdown == 1)
    {
        Console.WriteLine("FIRING SOLUTION LOCKED!");
    }
}

Console.WriteLine("FIRE! *BOOM* - Another planet gone... (thanks a lot, Imperial engineers)");

While-loopar - Ongoing Operations (Continue until mission complete)


int imperialShipsRemaining = 5;
int rebelAmmunition = 100;

Console.WriteLine("Engaging Imperial fleet...");

while (imperialShipsRemaining > 0 && rebelAmmunition > 0)
{
    Console.WriteLine($"Firing at Imperial ship! Ammunition: {rebelAmmunition}");

    rebelAmmunition -= 10;  // Each attack uses 10 ammunition
    imperialShipsRemaining--;  // Assume we hit (we're good shots, not Storm Troopers)

    Console.WriteLine($"Imperial ships remaining: {imperialShipsRemaining}");

    if (imperialShipsRemaining == 1)
    {
        Console.WriteLine("One enemy ship left! Focus fire!");
    }

    if (rebelAmmunition <= 30)
    {
        Console.WriteLine("WARNING: Low ammunition! Make every shot count!");
    }
}

if (imperialShipsRemaining == 0)
{
    Console.WriteLine("VICTORY! All Imperial ships destroyed!");
    Console.WriteLine("The Rebellion lives on!");
}
else
{
    Console.WriteLine("Out of ammunition! Tactical retreat recommended!");
    Console.WriteLine("We'll fight another day!");
}

Interactive Mission Briefing (Like C-3PO giving endless options)


string commandDecision = "";
bool missionActive = true;

while (missionActive)
{
    Console.WriteLine("\n=== REBEL COMMAND CENTER ===");
    Console.WriteLine("Admiral, what are your orders?");
    Console.WriteLine("1. Launch fighter attack");
    Console.WriteLine("2. Begin evacuation");
    Console.WriteLine("3. Contact other rebel cells");
    Console.WriteLine("4. Analyze Death Star plans");
    Console.WriteLine("5. End command session");
    Console.WriteLine("\nEnter command (1-5): ");

    commandDecision = Console.ReadLine();

    if (commandDecision == "1")
    {
        Console.WriteLine("Launching fighter attack! Red Squadron deploying!");
        Console.WriteLine("May the Force be with our pilots!");
    }
    else if (commandDecision == "2")
    {
        Console.WriteLine("Evacuation protocol activated! All personnel to escape pods!");
        Console.WriteLine("The rebellion will continue elsewhere!");
    }
    else if (commandDecision == "3")
    {
        Console.WriteLine("Contacting rebel cells across the galaxy...");
        Console.WriteLine("The network grows stronger!");
    }
    else if (commandDecision == "4")
    {
        Console.WriteLine("Analyzing Death Star structural weaknesses...");
        Console.WriteLine("Wait... there's something here... a small exhaust port...");
    }
    else if (commandDecision == "5")
    {
        Console.WriteLine("Command session ending. May the Force be with you, Admiral!");
        missionActive = false;  // End the mission
    }
    else
    {
        Console.WriteLine("Invalid command! Even C-3PO would understand the options better!");
        Console.WriteLine("Please try again, Admiral.");
    }
}

Foreach-loopar - Processing All Personnel/Equipment

Foreach är perfect för going through collections - som checking all pilots, all ships, eller all supplies:


string[] rebelPilots = { "Luke Skywalker", "Wedge Antilles", "Biggs Darklighter", "Jek Porkins" };

Console.WriteLine("=== RED SQUADRON ROLL CALL ===");
foreach (string pilot in rebelPilots)
{
    Console.WriteLine($"Pilot {pilot}, report for duty!");

    if (pilot == "Luke Skywalker")
    {
        Console.WriteLine("  - Special assignment: Death Star trench run");
        Console.WriteLine("  - May the Force be with you, Luke!");
    }
    else if (pilot == "Jek Porkins")
    {
        Console.WriteLine("  - Callsign: Red Six (RIP, we'll miss you Porkins)");
    }
}

Equipment Check (Making sure everything works better än Imperial engineering)


int[] shipConditions = { 95, 87, 92, 78, 65, 88, 91 };

Console.WriteLine("=== DAILY SHIP CONDITION REPORT ===");
int shipNumber = 1;

foreach (int condition in shipConditions)
{
    Console.WriteLine($"X-wing #{shipNumber}: {condition}% operational");

    if (condition >= 90)
    {
        Console.WriteLine($"  Status: EXCELLENT - Ready for Death Star runs!");
    }
    else if (condition >= 80)
    {
        Console.WriteLine($"  Status: GOOD - Ready for standard missions");
    }
    else if (condition >= 70)
    {
        Console.WriteLine($"  Status: NEEDS MAINTENANCE - Patrol duty only");
    }
    else
    {
        Console.WriteLine($"  Status: GROUNDED - Send to repair bay immediately!");
    }

    shipNumber++;
}

Praktiska exempel (Real Galactic Scenarios)

Example 1: Count Force-Sensitive Individuals


int totalPersonnel = 1000;
int forceSensitiveCount = 0;

Console.WriteLine("Scanning Rebel Alliance for Force-sensitive individuals...");

for (int personId = 1; personId <= totalPersonnel; personId++)
{
    // Simulate Force-sensitivity check (very rare - about 0.1% chance)
    if (personId % 347 == 0)  // Arbitrary rare condition
    {
        forceSensitiveCount++;
        Console.WriteLine($"Person #{personId}: FORCE-SENSITIVE detected!");
        Console.WriteLine("  - Recommended for Jedi training");
        Console.WriteLine("  - High priority protection status");
    }
}

Console.WriteLine($"\nSCAN COMPLETE:");
Console.WriteLine($"Total personnel scanned: {totalPersonnel}");
Console.WriteLine($"Force-sensitive individuals found: {forceSensitiveCount}");
Console.WriteLine($"The Force is strong with {forceSensitiveCount} of our people!");

if (forceSensitiveCount > 0)
{
    Console.WriteLine("Hope for the Jedi lives on!");
}

Example 2: Imperial Base Command Center (Complex Menu System)


string securityLevel = "HIGH";
bool baseOnAlert = false;
string operatorChoice = "";

while (operatorChoice != "LOGOUT")
{
    Console.WriteLine("\n=== IMPERIAL COMMAND CENTER ===");
    Console.WriteLine($"Security Level: {securityLevel}");
    Console.WriteLine($"Base Alert Status: {(baseOnAlert ? "ACTIVE" : "NORMAL")}");
    Console.WriteLine();
    Console.WriteLine("Available Commands:");
    Console.WriteLine("SCAN - Scan for rebel activity");
    Console.WriteLine("DEPLOY - Deploy TIE fighters");
    Console.WriteLine("ALERT - Raise base alert level");
    Console.WriteLine("STATUS - Show base status");
    Console.WriteLine("LOGOUT - End session");
    Console.WriteLine("\nEnter command: ");

    operatorChoice = Console.ReadLine().ToUpper();  // Convert to uppercase for consistency

    if (operatorChoice == "SCAN")
    {
        Console.WriteLine("Scanning local systems for rebel activity...");
        for (int system = 1; system <= 5; system++)
        {
            Console.WriteLine($"  System {system}: Clear");
        }
        Console.WriteLine("Wait... detecting small fighter signatures...");
        Console.WriteLine("REBEL ACTIVITY CONFIRMED!");
        baseOnAlert = true;
        securityLevel = "MAXIMUM";
    }
    else if (operatorChoice == "DEPLOY")
    {
        if (baseOnAlert)
        {
            Console.WriteLine("Deploying TIE fighter squadrons...");
            for (int squadron = 1; squadron <= 3; squadron++)
            {
                Console.WriteLine($"  TIE Squadron {squadron}: LAUNCHED");
            }
            Console.WriteLine("All fighters deployed! Hunt down those rebels!");
        }
        else
        {
            Console.WriteLine("No current threats detected. TIE fighters on standby.");
        }
    }
    else if (operatorChoice == "ALERT")
    {
        baseOnAlert = true;
        securityLevel = "MAXIMUM";
        Console.WriteLine("RED ALERT! ALL PERSONNEL TO BATTLE STATIONS!");
        Console.WriteLine("This is not a drill!");
    }
    else if (operatorChoice == "STATUS")
    {
        Console.WriteLine("=== BASE STATUS REPORT ===");
        Console.WriteLine($"Personnel: 50,000 Imperial troops");
        Console.WriteLine($"TIE Fighters: 144 operational");
        Console.WriteLine($"Shield Generator: Online");
        Console.WriteLine($"Main Reactor: Stable");
        Console.WriteLine($"Security Level: {securityLevel}");

        if (baseOnAlert)
        {
            Console.WriteLine("WARNING: Rebel activity detected in system!");
        }
    }
    else if (operatorChoice == "LOGOUT")
    {
        Console.WriteLine("Imperial Command session terminated.");
        Console.WriteLine("Long live the Emperor!");
    }
    else
    {
        Console.WriteLine("INVALID COMMAND! Are you a rebel spy?");
        Console.WriteLine("Security will be notified of this breach!");
    }
}

Example 3: Working med Rebel Pilot Objects (Advanced Tactical Management)


public class RebelPilot
{
    public string Name { get; set; }
    public string Callsign { get; set; }
    public int SkillLevel { get; set; }
    public bool IsForceUser { get; set; }
    public string Squadron { get; set; }
}

// Create nossa rebel pilot roster
List<RebelPilot> pilots = new List<RebelPilot>
{
    new RebelPilot { Name = "Luke Skywalker", Callsign = "Red Five", SkillLevel = 85, IsForceUser = true, Squadron = "Red" },
    new RebelPilot { Name = "Wedge Antilles", Callsign = "Red Two", SkillLevel = 95, IsForceUser = false, Squadron = "Red" },
    new RebelPilot { Name = "Biggs Darklighter", Callsign = "Red Three", SkillLevel = 80, IsForceUser = false, Squadron = "Red" },
    new RebelPilot { Name = "Jek Porkins", Callsign = "Red Six", SkillLevel = 70, IsForceUser = false, Squadron = "Red" }
};

// Mission assignment based on pilot abilities
Console.WriteLine("=== MISSION ASSIGNMENT PROTOCOL ===");
Console.WriteLine("Assigning pilots to Death Star assault mission...\n");

foreach (RebelPilot pilot in pilots)
{
    Console.WriteLine($"Pilot: {pilot.Name} ({pilot.Callsign})");
    Console.WriteLine($"Skill Level: {pilot.SkillLevel}/100");
    Console.WriteLine($"Force User: {(pilot.IsForceUser ? "Yes" : "No")}");

    // Mission assignment based on abilities
    if (pilot.IsForceUser && pilot.SkillLevel >= 80)
    {
        Console.WriteLine("MISSION: Death Star Trench Run - PRIMARY ASSAULT");
        Console.WriteLine("Special equipment: Targeting computer optional");
        Console.WriteLine("May the Force guide your shots!");
    }
    else if (pilot.SkillLevel >= 90)
    {
        Console.WriteLine("MISSION: Death Star Trench Run - COVER FORMATION");
        Console.WriteLine("Protect the primary assault pilot!");
    }
    else if (pilot.SkillLevel >= 75)
    {
        Console.WriteLine("MISSION: TIE Fighter Engagement");
        Console.WriteLine("Clear the path for trench runners!");
    }
    else
    {
        Console.WriteLine("MISSION: Base Defense");
        Console.WriteLine("Guard the rebel base - equally important!");
    }

    Console.WriteLine("-------------------");
}

// Find our best pilots för special missions
Console.WriteLine("\n=== SPECIAL OPERATIONS CANDIDATES ===");
foreach (RebelPilot pilot in pilots)
{
    if (pilot.SkillLevel >= 85 || pilot.IsForceUser)
    {
        Console.WriteLine($"HIGH-PRIORITY PILOT: {pilot.Name}");
        if (pilot.IsForceUser)
        {
            Console.WriteLine("  - Force abilities detected: Perfect för impossible shots!");
        }
        if (pilot.SkillLevel >= 90)
        {
            Console.WriteLine("  - Elite skill level: Squadron leader material!");
        }
    }
}

Vanliga misstag att undvika (Don’t make Storm Trooper-level mistakes)

Misstag 1: Oändlig loops (Like being stuck in a tractor beam)


// FEL - Infinite loop som never ends (like Imperial bureaucracy)
int countdown = 10;
while (countdown > 0)
{
    Console.WriteLine($"Death Star charging: {countdown}");
    // GLÖMDE: countdown--;
    // This loop runs forever! Death Star never fires!
}

// RÄTT - Always ensure loop condition eventually becomes false
int countdown = 10;
while (countdown > 0)
{
    Console.WriteLine($"Death Star charging: {countdown}");
    countdown--;  // CRITICAL: Decrease countdown!
}
Console.WriteLine("Death Star fired! (Unfortunately for some planet...)");

Misstag 2: Assignment istället för Comparison (Like confusing attack orders)


int targetShips = 5;

// FEL - Using assignment (=) instead of comparison (==)
if (targetShips = 3)  // This SETS targetShips to 3, doesn't compare!
{
    Console.WriteLine("Engaging 3 ships!");  // Always executes!
}

// RÄTT - Use comparison operator
if (targetShips == 3)  // This COMPARES targetShips to 3
{
    Console.WriteLine("Engaging exactly 3 ships!");
}

Misstag 3: Scope Problems med Braces (Like giving orders to wrong squadron)


bool underAttack = true;
bool hasEscorts = false;

// FEL - Without braces, only first statement is conditional
if (underAttack)
    Console.WriteLine("Red alert! All fighters scramble!");
    Console.WriteLine("Protect the transport ships!");  // ALWAYS executes!

// RÄTT - Use braces för clarity (like proper military commands)
if (underAttack)
{
    Console.WriteLine("Red alert! All fighters scramble!");
    Console.WriteLine("Protect the transport ships!");  // Now both execute only if under attack
}

Misstag 4: Logical Operator Confusion (Like mixed up battle communications)


bool hasShields = false;
bool hasWeapons = true;

// FEL - Using AND when you meant OR
if (hasShields && hasWeapons)  // Both must be true - very restrictive!
{
    Console.WriteLine("Ship combat ready!");
}

// RÄTT - Using OR when you want either condition
if (hasShields || hasWeapons)  // Either one is enough för basic combat
{
    Console.WriteLine("Ship can engage in combat!");
}

Switch Case - The Command Center Navigation (Choosing Your Path Wisely)

När du har många olika choices att välja mellan, är switch-case som Death Star command center - en central kontroll som router commands based på input. Perfect för navigation menus och command selections!

Basic Switch (Command Selection)


int commandChoice = 2;

switch (commandChoice)
{
    case 1:
        Console.WriteLine("ATTACK - Engage enemy forces!");
        Console.WriteLine("All fighters, commence attack run!");
        break;

    case 2:
        Console.WriteLine("DEFEND - Raise shields and hold position!");
        Console.WriteLine("Protect the fleet at all costs!");
        break;

    case 3:
        Console.WriteLine("RETREAT - Fall back to rendezvous point!");
        Console.WriteLine("Live to fight another day!");
        break;

    case 4:
        Console.WriteLine("RECON - Send out probe droids!");
        Console.WriteLine("Gather intelligence before acting!");
        break;

    default:
        Console.WriteLine("Invalid command! Even C-3PO knows better protocols!");
        break;
}

Switch med String (Pilot Callsign Recognition)


string pilotCallsign = "Red Five";

switch (pilotCallsign)
{
    case "Red Leader":
        Console.WriteLine("Garven Dreis - Red Squadron Leader");
        Console.WriteLine("Status: Experienced leader, ready for Death Star run");
        break;

    case "Red Five":
        Console.WriteLine("Luke Skywalker - The Hope of the Galaxy");
        Console.WriteLine("Status: Force-sensitive, cleared for trench run");
        break;

    case "Red Two":
        Console.WriteLine("Wedge Antilles - Veteran Pilot");
        Console.WriteLine("Status: Reliable wingman, excellent survival record");
        break;

    case "Red Six":
        Console.WriteLine("Jek Porkins - Heavy Fighter Specialist");
        Console.WriteLine("Status: 'I can hold it!' (Famous last words...)");
        break;

    default:
        Console.WriteLine($"Pilot {pilotCallsign} not found in database");
        Console.WriteLine("Please verify callsign with flight control");
        break;
}

Praktiskt exempel - Rebel Command Menu


Console.WriteLine("=== REBEL ALLIANCE COMMAND CENTER ===");
Console.WriteLine("1. Attack Imperial forces");
Console.WriteLine("2. Defend current position");
Console.WriteLine("3. Evacuate base");
Console.WriteLine("4. Launch reconnaissance");
Console.WriteLine("5. Contact other rebel cells");
Console.WriteLine("6. Review battle plans");
Console.WriteLine("0. End command session");

int userChoice = int.Parse(Console.ReadLine());

switch (userChoice)
{
    case 1:
        Console.WriteLine("ATTACK INITIATED");
        Console.WriteLine("All squadrons report to fighters immediately!");
        Console.WriteLine("May the Force be with our brave pilots!");
        break;

    case 2:
        Console.WriteLine("DEFENSIVE POSITIONS");
        Console.WriteLine("All personnel to battle stations!");
        Console.WriteLine("Shields to maximum, weapons online!");
        break;

    case 3:
        Console.WriteLine("EVACUATION PROTOCOL ACTIVATED");
        Console.WriteLine("This is not a drill! All personnel to escape pods!");
        Console.WriteLine("Transport ships prepare for immediate departure!");
        break;

    case 4:
        Console.WriteLine("RECONNAISSANCE MISSION");
        Console.WriteLine("Sending probe droids to gather intelligence...");
        Console.WriteLine("Stealth is our ally - avoid Imperial detection!");
        break;

    case 5:
        Console.WriteLine("COMMUNICATIONS ESTABLISHED");
        Console.WriteLine("Contacting rebel cells across the galaxy...");
        Console.WriteLine("Hope spreads through secure channels!");
        break;

    case 6:
        Console.WriteLine("BATTLE PLANS ACCESSED");
        Console.WriteLine("Reviewing Death Star attack strategies...");
        Console.WriteLine("The weakness in the thermal exhaust port confirmed!");
        break;

    case 0:
        Console.WriteLine("Command session terminated. May the Force be with you!");
        break;

    default:
        Console.WriteLine("Invalid command code!");
        Console.WriteLine("Even Imperial droids follow better protocols!");
        Console.WriteLine("Please select a valid option from the menu.");
        break;
}

Switch vs If-else if (När använder du vad?)

Använd Switch när:

  • Du har en variabel som jämförs med många exact values
  • Värdena är constants (numbers, strings, chars)
  • Du vill ha clean, readable code som navigation menu

Använd If-else if när:

  • Du behöver ranges (som age >= 18)
  • Du har complex conditions (pilot.skill > 90 && pilot.hasForceAbilities)
  • Du jämför different variables i varje condition

// SWITCH - Perfect för exact matches (som callsigns)
switch (shipType)
{
    case "X-wing": /* ... */ break;
    case "Y-wing": /* ... */ break;
    case "A-wing": /* ... */ break;
}

// IF-ELSE IF - Perfect för ranges och complex conditions
if (pilotExperience >= 100 && hasForceAbilities)
{
    // Elite Force-user pilot
}
else if (pilotExperience >= 50)
{
    // Experienced regular pilot
}
else
{
    // Rookie pilot
}

Sammanfattning (Tactical Command Summary)

  • If-satser make tactical decisions based on battle conditions (enemy strength, resources, etc.)
  • Switch-case handles multiple exact choices efficiently (som command menus och navigation)
  • Comparison operators (==, !=, >, <, >=, <=) assess battlefield situations
  • Logical operators (&&, ||, !) combine multiple battle conditions för complex decisions
  • For-loopar execute precise, counted operations (launching fighters, countdown sequences)
  • While-loopar continue operations until mission objectives met (ongoing battles)
  • Foreach-loopar process all personnel, equipment, eller data systematically
  • Always use braces för clarity i complex tactical scenarios
  • Test loop exit conditions - infinite loops are worse än Imperial bureaucracy!
  • Use switch för exact matches, if-else för ranges och complex conditions

Remember: “The Force can have a strong influence on the weak-minded” - Obi-Wan Kenobi. Men strong logical flow har a strong influence on readable code! Master these control structures, och your programs will execute som smoothly som a successful Death Star assault!

Good tactical programming är like good battle strategy - clear decisions, proper repetition, och always plan your exit strategy!

May the Logical Flow be with you!

Föregående: Kapitel 3 - Klasser: Building the Rebel Alliance Nästa: Kapitel 5 - Listor och praktiska verktyg: The Rebel Arsenal


Upp

Upp


Licens: Apache 2.0 | © 2023 Marcus Medina, Campus Mölndal. Alla rättigheter förbehållna.
Du får använda och modifiera detta verk enligt villkoren i Apache License, Version 2.0. Du får inte använda detta verk för kommersiella ändamål utan tillstånd från upphovsmannen.