1. Java If... Else 문
: 자바는 많은 논리 연산 조건을 가지고 있다. 예를 들면 (a <b, a <=b, a==b, a!=b)등이 있다. 이를 활용해서 if... else문을 통해 많은 결괏값을 도출할 수 있다.
• if 문: Specifying a block of code to be executed if a specified condition is true.
• else 문: Specifying a block of code to be executed, if the same condition is false.
• else if 문: Specifying a new condition to test, if the first condition is false.
• switch 문: Specifying many alternative blocks of code to be executed
- if문:
if (condition) {
// block of code to be executed if the condition is true
}
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}
- else 문:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
- else if문:
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
- if... else 축약문
: 삼향 연산자(ternary operator)라고도 한다. 왜냐하면 a, b, c 세 개의 피연산자가 들어가고, 조간 a가 true이면 b를 false면 c를 리턴하는 연산자 이기 때문이다. 이를 활용하면 여러 줄의 조건문을 한 줄에 정리할 수 또 있다.
variable = (condition) ? expressionTrue : expressionFalse;
이러한 형식으로 쓰인다.
예를 들어서
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
이런 여러 줄의 조건문을
int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);
이렇게 축약할 수 있다.
- switch 문
: 여러 줄에 if... else문을 사용하는 대신에 switch문을 사용할 수 도 있다.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the associated code block is executed.
- The break and default keywords are optional and will be described later in this chapter
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
- break 키워드
: break를 통해서 다른 코드를 실행시키지 않게 한다. 왜냐하면 조건에 만족하는 코드를 실행하고 그 뒤에 있는 스위치 블록들을 전부 무시하기 때문이다. break가 없었으면 위에 코드는 "code 4" 이후에 모든 값을 출력했을 것이다.
2. 반복문
반복문(Loop): 일정한 조건을 만족할 때까지 code block을 반복 실행 해 준다. 이를 통해 반복적인 작업을 프로그램이 대신 실행해 시간을 아끼고, 에러를 줄이고, 코드의 가독성을 좋게 해 준다.
- While반복문
: 일정 조건이 참일 때까지 코드를 반복 실행하는 반복문중 하나이다. 기본형은 다음과 같다.
while (condition) {
// code block to be executed
}
while loop를 사용하면 i가 정수 5와 작거나 같을 때까지 i값에 1을 추가하는 코드를 만들 수 있다.
int i = 0;
while (i <= 5) {
System.out.println(i);
i++;
}
- Do/While 반복문
: While문과 비슷하게 일정 조건을 만족할 때까지 코드를 반복 실행 하는 건 같지만, while 반복문을 실행하기 전에 또 다른 일정 조건을 만족시켜야지만 while문을 실행하는 차이가 있다. 기본형은 다음과 같다.
do {
// code block to be executed
}
while (condition);
Do/While 반복문은 아무리 조건이 false여도 항상 적어도 한 번은 실행해야 한다. 왜냐하면 코드가 실행되기 전에 일정 조건을 만족시키는지 test를 하기 때문이다.
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
- For 반복문
: 반복문을 몇 번 실행할지 정확히 알고 있을 때는 while loop보단 for loop를 사용하면 효율적으로 코드를 실행시킬 수 있다. 기본형을 다음과 같다.
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed(every time) after the code block has been executed.
예시로 0부터 5까지 숫자를 출력하는 for반복문을 만들어보자
for (int i = 0; i <= 5; i++) {
System.out.println(i);
}
: Statement 1 (int i = 0)는 반복문을 실행하기 전에 변수를 정하는 것이다 이경우에는 i (shorts for index)를 integer로 설정해 준다.
Statement2 (i <= 5)는 반복문을 실행하기 위한 조건을 설정하는 것이다. 조건이 true일 시에 반복문을 실행하고 false일 때에는 반복문을 중단한다. 이경우에는 조건이 i가 5보다 작거나 같을 때까지 반복하는 것이다.
Statement3 (i++)는 i를 반복문이 실행할 때마다 1씩 증가시킨다는 것이다.
이 코드를 실행시켰을 때에 정수형 변수 i는 0이라는 값을 가지고 0은 5보다 작거나 같은 조건에 충족하기 때문에 0을 출력하고 i는 1만큼 증가하고 다시 for 반복문을 실행한다. 이번에도 i가 정수 1의 값을 가지고 있기 때문에 똑같은 반복문이 실행되고 i가 1만큼 계속 증가하다가 5가 되었을 때 반복문은 중단된다. 그렇게 해서 이 코드를 실행시켰을 때에 출력 결괏값은 다음과 같다.
0
1
2
3
4
5
다른 비슷한 예를 들자면, int i = 0이 정수 10과 작거나 같아질 때까지 2씩 증가하는 실행하는 반복문을 만들 수 있다
for (int i = 0; i <= 10; i = i + 2) {
System.out.println(i);
}
- Nested Loops(중첩 루프)
: 반복문안에 반복문을 넣은 반복문을 말한다. inner loop을 outer loop이 반복하는 만큼 실행한다. 말이 어려우니 예시 코드를 보자
// Outer loop
for (int i = 1; i <= 2; i++) {
System.out.println("Outer: " + i); // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; j++) {
System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
}
}
Outer loop에서는 정수 1의 값을 가진 변수 i가 2의 값을 가질 때까지 증가 즉 두 번 반복문을 실행한다. 그러면 Outer loop안에 있는 Inner loop는 정수 1의 값을 가진 변수 j를 3의 값과 같아질 때까지 반복문을 두 번 실행시킨다. 결과 값을 보면 이해가 더 쉽다.
Outer: 1
Inner: 1
Inner: 2
Inner: 3
Outer: 2
Inner: 1
Inner: 2
Inner: 3
- For-Each 반복문
: array의 요소(elements)를 반복시키는 특수한 경우에 사용한다. 예시 코드를 살펴보자.
for (type variableName : arrayName) {
// code block to be executed
}
밑에 예시는 cars어레이를 for each문을 사용해서 어레이 안에 요소들을 출력시키는 코드이다.
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
}
}
그래서 Array가 뭔데... 그래서 준비했다
3. Arrays(어레이)
: Python에서 딕셔너리와 비슷하게 여러 가지 value들을 한 가지 변수에 넣는 것을 말한다. 어레이를 선언하기 위해서는 함수 타입을 선언하고 그 뒤에 square brackets "[ ]"을 차원의 수만큼 넣어주면 된다.
STring[] cars;
어레이를 생성하려면 그 안에 value들을 curly brackets"{ }" 안에 넣어야 한다. 각각의 value들은 쉼표", "를 통해서 나뉜다. 그러고 반드시 각각의 value들은 동일한 type을 가져야만 한다.
String[] cars = {"Volvo", "BMW", "Ford", "Manda"};
String 형 value를 가진 어레이
int[] myNum = {10, 20, 30, 40};
정수형 value를 가진 어레이
- Array안에 특정 요소(Element)만 사용하기
: index number를 사용하면 쉽게 access 할 수 있다. (0부터 count 한 다는 점을 명심하자)
Array안에 첫 번째 요소 꺼내기:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo
Array안에 요소 변경하기:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel"; //첫 번쨰 요소"Volvo"를 "Opel"로 변경
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
- Array와 Loop(반복문)
eg) for문
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
Volvo
BMW
Ford
Mazda
eg2) for-each문
기본형은 다음과 같다.
for (type variable : arrayname) {
...
}
cars array안에 있는 모든 요소들을 for-each반복문을 사용해 출력한 예
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
Volvo
BMW
Ford
Mazda
- Multidimensional Array (다차원의 어레이)
: 다차원의 어레이는 열과 행을 가진 테이블 등 tabular data(표를 사용하는 데이터)를 다룰 때 매우 유용하게 사용된다.
2차원의 어레이를 만들기 위해선 자료 타입을 선언하고 그 옆에 square brackets"[ ]"을 두 개 붙여준 뒤에, 각각의 어레이들을 또 다른 curly brackets "{ }"안에 넣으면 된다.
int[][] myNumbers = {{ 1, 2, 3, 4}, { 5, 6, 7}};
해당 변수는 각각의 요소를 가지고 있는 두 개의 어레이의 어레이가 된 것이다. 호고곡....
Array 안에 있는 Array 안에 있는 요소들을 꺼내기 위해선 그 요소의 인덱스 위치를 입력하면 된다. ez
eg. 2차원 어레이 안에 있는 두 번째 어레이안에 있는 3번째 요소를 꺼내는 코드
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]);
// Outputs 7
: 변경도 array 요소 변경할 때와 마찬가지로 하면 된다.
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers[1][2] = 9; // 2차원 어레이 안에 있는 세 번째 어레이의 세번째 요소 7을 9로 변경
System.out.println(myNumbers[1][2]);
// Outputs 9 instead of 7
: 다차원 array에서의 반복문
public class Main {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} }; // 1)
for (int i = 0; i < myNumbers.length; ++i) { // 2)
for(int j = 0; j < myNumbers[i].length; ++j) { // 3)
System.out.println(myNumbers[i][j]); // 4)
}
}
}
}
1)에서는 2차원 배열 myNumbers를 선언하고 초기화합니다. 이 배열은 2개의 행을 가지고 있으며, 첫 번째 행에는 1, 2, 3, 4가, 두 번째 행에는 5, 6, 7이 들어있습니다.
2)에서는 외부 반복문: 배열의 행을 반복합니다. myNumbers.length는 배열의 행의 개수를 나타냅니다.
3)에서는 내부 반복문: 현재 행에 대한 열을 반복합니다. myNumbers[i].length는 현재 행의 열의 개수를 나타냅니다.
마지막으로 4)에서는 현재 행과 열에 해당하는 배열 요소를 출력합니다.
'AIoT' 카테고리의 다른 글
AIoT 정규 22일차 (0) | 2024.01.29 |
---|---|
AIoT 정규 21일차 (1) | 2024.01.26 |
AIoT 정규 19일차 (1) | 2024.01.24 |
AIoT 정규 18일차 (1) | 2024.01.23 |
AIoT 정규 17일차 (0) | 2024.01.22 |