Home > Back-end >  How do I exit While Loop and execute else if statement and array in swift?
How do I exit While Loop and execute else if statement and array in swift?

Time:10-06

Ive created program that runs while loop and will execute loop until it reaches 150 "rebels eliminated". I utilize break statement to end the while loop from turning into infinite loop. I want to add another block code which is else if statement that once loop reaches 150 "rebels eliminated" it will execute that specific block code! Im having no luck and would like seek guidance. Should I utilize function? I also created array for program allow user pick blaster. After the else if Statement I want array be executed. Whats best way go about this?

import UIKit

var health = 5
var stormTrooperBlasterReload = false
var magazineCaptivity = 0
var rebelsEliminated = 0
var sprinting = 0
var speed = 0
var switchBlaster: String? = ""
var inventory: [String] = ["blasterPistol", "blasterRifle", "blasterShotgun"]


//ends the loop once it reaches 800
while health > 0 {
    if rebelsEliminated == 150 {
        print("The emperor has rised!")
        while sprinting > 50 {
            if sprinting < 50 {
                print("you need to speed up")
            }else if
                sprinting == 50 || sprinting > 50{
                print("you are moving fast")
            }else{
                print("Sprint!")
                break
            }
        }
  }
    if stormTrooperBlasterReload {
        print("you are reloading, Take cover!")
        sleep(7)
        print("reloading almost complete!")
        sleep(2)
        print("aiming your blaster")
        stormTrooperBlasterReload = false
        magazineCaptivity = 0
    }
    if magazineCaptivity > 50 {
        stormTrooperBlasterReload = true
        continue
    }
    print("Firing")
    magazineCaptivity  = 1
    rebelsEliminated  = 1

CodePudding user response:

Check this block of code.

      while sprinting > 50 {
            if sprinting < 50 {
                print("you need to speed up")
            }else if
                sprinting == 50 || sprinting > 50{
                print("you are moving fast")
            }else{
                print("Sprint!")
                break
            }
        }

Here, your while loop condition first check if sprinting is greater than 50. So it will only execute this part.

if sprinting == 50 || sprinting > 50{
   print("you are moving fast")
}

So your loop will never reach it

        }else{
            print("Sprint!")
            break
        }
  • Related