if/else, for/while, switch 등등 Statement 정리.
void main() {
int number = 3;
if(number % 3 == 0){
print('나머지가 0입니다.');
} else if(number % 3 == 1){
print('나머지가 1입니다.');
} else {
print('나머지가 2입니다.');
}
}
void main() {
int number = 1;
switch(number % 3){
case 0:
print('나머지가 0입니다.');
break;
case 1:
print('나머지가 1입니다.');
break;
default:
print('나머지가 2입니다.');
break;
}
}
반복적인 작업을 사용할때 유용함.
void main() {
for(int i = 0; i < 10; i++){
print(i);
}
}
void main() {
int total = 0;
List<int> numbers = [1, 2, 3, 4, 5, 6];
for(int i = 0; i < numbers.length; i++){
total += numbers[i];
}
}
를 아래와 같이 표현할 수 있다.
void main() {
int total = 0;
List<int> numbers = [1, 2, 3, 4, 5, 6];
for(int number in numbers){
total += number;
}
}
그 외 활용법
void main() {
//continue
for(int i = 0; i < 10; i++){
if(i == 5){
continue;
}
print(i);
/* 0
* 1
* 2
* 3
* 4
* 6
* 7
* 8
* 9
*/
}
}
void main() {
// 1. while
int total = 0;
while(total < 10){
total += 1;
}
print(total);
// 10
// 2. while break
total = 0;
while(total < 10){
total += 1;
if(total == 5){
break;
}
}
print(total);
// 10
// 3. do while. 거의 안씀
total = 0;
do {
total += 1;
} while(total < 10);
print(total);
// 10
}
continue
, break
등등 다양한 Statement에서 사용할 수 있다.
reference