[LIKELION] 220921

고관운·2022년 9월 21일
0

회고

😭 느낀점

  • 어제 코로나에 확진된 후 컨디션이 좋지 않았지만 조금씩 회복중이다.
  • 오랜만에 09 ~ 18시 교육이라 힘들지만 몰랐던 점들을 자세하게 배울 수 있어서 좋은 것 같다.
  • 기술 블로그를 오늘 처음으로 작성하는데 내가 배운 내용을 다시 한번 정리할 수 있어서 좋다.

😁 목표

  • 과제 2개 완료하기
  • 프로그래머스 코딩 연습

01. 자바-03-형변환

상수

상수 : 수정 불가능한 숫자
선언시 키워드 final이 앞에 붙으며 한번만 할당 가능

🔴 상수 변수명에 대한 표기법은 모두 대문자로 (다른 단어가 나온다면 언더바를 중간에 넣기)
ex) MAX_VALUE

상수 할당 방법 2가지

final int MAX_VALUE = 10;
final int MAX_VALUE;
MAX_VALUE = 10;

실습. 반지름이 5인 원의 넓이 출력하기

public class pi {

	public static void main(String[] args) {
		final double PI = Math.PI;
		int radius = 5;
		
		System.out.println(radius * radius * PI);
	}
}

형변환

형변환 하는 이유 : 컴퓨터는 연산시 데이터 타입이 같아야 하기 때문이다.

🟢 long num2 = 3147483647L;
여기서 L의 의미는 앞의 정수를 long 타입으로 바꾼다는 뜻이다.

자동 형변환

🔴 자료형 크기가 큰 방향으로 변환
단, 정수형보다는 실수형으로 변환 (소수점을 보존하기 위해서)

명시적 형변환

아래 코드와 같이 강제로 형변환시킴

int num = (int)pi;

실습

숫자를 입력받고 문자로 출력, 문자를 입력받고 숫자로 출력

import java.util.Scanner;

public class practice2 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		int nums = sc.nextInt();
		System.out.println((char) nums);
		
		sc.nextLine();
		
		char ch = sc.nextLine().charAt(0);
		System.out.println((int) ch);
	}

}

02. 자바-04-연산자

연산자

연산자 우선순위

🔴 결합방향 : 우선순위가 같을 경우, 연산 순서 방향
🔴 ( ) 괄호는 최우선 연산자

문자열 연산자

문자열과 숫자가 있으면 문자열 로 결합

String str3 = "JDK" + 3 + 3.0;
String str4 = 3 + 3.0 + "JDK";

🔴 해당 코드를 실행시켰을 때, str3는 JDK33.0, str4는 6.0JDK 차이점 알아두기

복합 대입 연산자

a = x++; : x의 값을 a에 대입한 후, x의 값에 1을 더하기
b = ++y; : y의 값에 1을 더한 후, y의 값을 b에 대입하기

관계연산자 및 논리 연산자

&& : AND
|| : OR
! : NOT

삼항 연산자

(a < b) ? c : d 참이면 c, 거짓이면 d

실습

3개의 숫자 중 max 값을 삼항 연산자로 구하기


public class practice4 {

	public static void main(String[] args) {
		int num1 = 10;
		int num2 = 20;
		int num3 = 30;
		
        int max = (num1 < num2) ? num2 : num1;
        max = (max < num3) ? num3 : max;
        
		System.out.println(max);	
	}
}

03. 자바-05-반복문

while문

while문이란?

while문의 괄호에는 참 거짓을 판별할 수 있도록 넣어라
(참이면 수행, 거짓이면 탈출)

실습. 특정 문장 5번 반복 출력

public class practice5 {

	public static void main(String[] args) {
		int num = 0;
		
		while(num < 5) {
			System.out.println("I like Java " + num);
			num++;
		}
    }
}

실습. 1~10 합계

public class practice5 {

	public static void main(String[] args) {
		int num1 = 1;
		int result = 0;
		
		while(num1 &< 11) {
			result += num1;
			num1++;
		}
		
		System.out.println("합계=" + result);
    }
}

do while문

do whiel문이란?

중괄호 영역은 무조건 한번 먼저 실행, 이후는 while문과 동일

for문

for문 작동 순서

  1. 초기식
  2. 조건식
  3. 반복문장
  4. 증감식
    이후 2~4 반복 수행, 2번 조건에 맞지 않으면 탈출

실습. 숫자를 입력받아 해당 구구단 출력

import java.util.Scanner;

public class practice5 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		int num2 = sc.nextInt();
		
		for (int i = 1; i < 10; i++) {
			System.out.println(num2 + "*" + i + "=" + (num2 * i));
		}
    }
}

continue & break

개념

continue : 반복문 중에 만나면 다음 조건 검사로 이동
break : 반복문 중에 만나면 반복문 탈출

실습. 5와 7의 최소공배수를 구하라 (break 사용)

public class practice5 {

	public static void main(String[] args) {
		int num3 = 1;
		while(true) {
			if(num3 % 5 == 0 && num3 % 7 == 0) {
				System.out.println(num3);
				break;
			}
			num3++;
		}
    }
}

실습. 1~100 숫자 중 5와 7의 배수를 아래와 같은 형태로 출력 (continue 사용)

35
70
count : 2

public class practice5 {

	public static void main(String[] args) {
		int cnt = 0;
		for(int i = 1; i <= 100; i++) {
			if(!(i % 5 == 0 && i % 7 == 0)) {
				continue;
			}
			System.out.println(i);
			cnt++;
		}
		System.out.println("count : " + cnt);
    }
}

알아두면 좋은 팁

while((num++) < 100) 이런식으로 사용할 수 있음
|| 의 경우 앞이 false면 뒤에 조건은 보지 않음

소스코드 정리 방법
코드 전체선택 -> Ctrl + Shift + F

실습

이중 for문 구구단

public class practice5 {

	public static void main(String[] args) {
		for(int i = 2; i < 10; i++) {
			for(int j = 1; j < 10; j++) {
				System.out.println(i + " X " + j + " = " + (i * j));
			}
		}
		
		System.out.println();
	}
}

구구단 중 짝수단만

public class practice5 {

	public static void main(String[] args) {
		for(int i = 2; i < 10; i++) {
			if(i % 2 != 0) {
				continue;
			}
			for(int j = 1; j < 10; j++) {
				System.out.println(i + " X " + j + " = " + (i * j));
			}
		}
	}
}

5 * 5 별 그리기

*****
*****
*****
*****
*****

public class practice5 {

	public static void main(String[] args) {
    	for(int i = 0; i < 5; i++) {
			for(int j = 0; j < 5; j++) {
				System.out.print('*');
			}
			System.out.println();
		}
	}
}

1 ~ 5개 별 단계적으로 그리기

*
**
***
****
*****

public class practice5 {

	public static void main(String[] args) {
		for (int i = 1; i <= 5; i++) {
			for (int j = 0; j < i; j++) {
				System.out.print('*');
			}
			System.out.println();
		}
	}
}

5 ~ 1개 별 단계적으로 그리기

*****
****
***
**
*

public class practice5 {

	public static void main(String[] args) {
		for (int i = 5; i >= 1; i--) {
			for (int j = 0; j < i; j++) {
				System.out.print('*');
			}
			System.out.println();
		}
	}
}

1 ~ 5개 별 단계적으로 그리기(오른쪽 정렬)

    *
   **
  ***
 ****
*****

public class practice5 {

	public static void main(String[] args) {
		for (int i = 5; i >= 1; i--) {
			for (int j = 0; j < i; j++) {
				System.out.print('*');
			}
			System.out.println();
		}
	}
}

자바-06-배열

배열

배열이란?

1000개의 int형이 필요할 경우 1000개를 모두 선언하기 어려우므로 배열이 필요함.

배열 선언

int[] s; int s[]; 모두 가능하지만 자바에서는 int[] s를 많이 사용함

  • 방법 2가지
    int[] s = new int[10]; 여기서 10은 배열의 크기
    int[] scores = {1,2,3,4,5}

🔴 배열 변수의 메모리에는 첫 인덱스값의 메모리 주소값이 들어가게 됨
(배열은 반드시 연속된 메모리에 들어간다)

알아두면 좋은 팁

  • arr.length : 배열 arr의 크기
  • 랜덤 함수 : (int)(Math.random()*100) + 1 1 ~ 100까지 랜덤 수
  • System.out.println(Arrays.toString(arr2)); 배열 형식으로 출력

실습

크기가 1000인 배열을 만들고 1 ~ 1000의 값을 넣고 총합 구하기

500500

public class practice6 {

	public static void main(String[] args) {
		int[] arr1 = new int[1000];
		int result = 0;
		
		for(int i = 0; i < 1000; i++) {
			arr1[i] = i + 1;
		}
		for(int tmp : arr1) {
			result += tmp;
		}
		System.out.println(result);
	}

}

크기가 10인 배열을 만들고 1 ~ 100 사이의 랜덤한 정수를 넣은 후 최대값 구하기

import java.util.Arrays;

public class practice6 {

	public static void main(String[] args) {
    	int[] arr2 = new int[10];
		int maxValue = 0;
		
		for(int i = 0; i < 10; i++) {
			arr2[i] = (int)(Math.random()*100) + 1;
		}
		for(int num : arr2) {
			if(maxValue < num) {
				maxValue = num;
			}
		}
		System.out.println(Arrays.toString(arr2));
		System.out.println(maxValue);
	}
}

로또 배열 선언한 후 1 ~ 45 사이의 랜덤한 숫자를 넣고 출력하시오 (단, 중복없이)

public class practice6 {

	public static void main(String[] args) {
		int[] arr3 = new int[6];
		for(int i = 0; i < arr3.length; i++) {
			arr3[i] = (int)(Math.random()*45) + 1;
			
			for(int j = 0; j < i; j++) {
				if(arr3[i] == arr3[j]) {
					i--;
					break;
				}
			}
		}
		System.out.println(Arrays.toString(arr3));
	}
}

0개의 댓글