Skip to content

Control Flow

Liu Siwei edited this page Aug 20, 2017 · 8 revisions

Executing different pieces of code based on certain conditions.

If Statement

Executing a set of statements only if a specified condition is true:

if value > 0 {
	// do something
}

The if statement can provide an alternative set of statements, known as an else clause, for situations when the if condition is false. These statements are indicated by the else keyword:

if value > 0 {
	// do something
} else {
	// do something else
}

Complex if statement:

if value > 10 {
	// do something
} else if value > 0 {
	// do something else
} else if value == 0 {
	// do something else
} else {
	// do something else
}

Switch Statement

The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.

char := "z"
switch char {
	case "a":
		print("The first letter of the alphabet")
	case "z":
		print("The last letter of the alphabet")
	default:
		print("Some other character")
}
// output "The last letter of the alphabet"

Similar to Swift programming language, switch statements in YJLO Script do not fall through the bottom of each case and into the next one by default. Thus, the explicit break statement at the end of each case is not required. However, using break inside the switch statement causes the switch statement to end its execution immediately and to transfer control to the code after the switch statement’s closing brace (}).

To make a switch with a single case that matches multiple values, combine these values into a compound case, separating the values with commas.

month := 2
year := 2020
numDays := 0

switch month {
	case 1, 3, 5, 7, 8, 10, 12:
		numDays = 31
	case 4, 6, 9, 11:
		numDays = 30
	case 2:
		if (((year % 4 == 0) && 
			 !(year % 100 == 0))
			|| (year % 400 == 0))
			numDays = 29
		else
			numDays = 28
	default:
		print("Invalid month.")
}
print("Number of Days = " + numDays)

If you need C-style fallthrough behavior, you can add a fallthrough statement at the end of the case clause.

integerToDescribe := 5
description := "The number " + integerToDescribe + " is"
switch integerToDescribe {
	case 2, 3, 5, 7, 11, 13, 17, 19:
		description += " a prime number, and also"
		fallthrough
	default:
		description += " an integer."
}
print(description)
// output "The number 5 is a prime number, and also an integer."

Introduction

Langauge Guide

Libraries

  • Utility
    • ListUtil
    • StringUtil
    • Math
  • Data Structure
    • LinkedList
    • Stack
    • Heap
    • HeapList
    • HashMap
    • HashSet
  • Others
    • UnitTest
    • Tokenizer

Dev Reference

  • Syntax Sugar
Clone this wiki locally