- week enum, 메소드 활용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class EnumWeekEx2 {
public static void main(String[] args) {
Week today = Week.SUNDAY;
String name = today.name(); //상수값을 문자값으로 변환
System.out.println(name);
int ordinal = today.ordinal(); //상수의 위치값 리턴
System.out.println(ordinal);
Week day1 = Week.MONDAY;
Week day2 = Week.FRIDAY;
int result1 = day1.compareTo(day2); //날짜 값 차이
int result2 = day2.compareTo(day1);
System.out.println(result1);
System.out.println(result2);
String day = "FRIDAY";
Week weekday = Week.valueOf(day); //문자를 상수로 변환
if (weekday==Week.SATURDAY||weekday==Week.SUNDAY) {
System.out.println("주말");
}else {System.out.println("평일");}
}
}
|
cs |
//
SUNDAY
6
-4
4
- 향상된 for문 (배열만 가능)
for(타입 변수:배열명){
...
}
public class ForEx1 {
public static void main(String[] args) {
int sum=0;
int[] nums = {25,78,36,45,30};
for (int num:nums) {
sum+=num;
}
System.out.println(sum);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public class EnumWeekEx2 {
public static void main(String[] args) {
Week today = Week.SUNDAY;
String name = today.name(); //상수값을 문자값으로 변환
System.out.println(name);
int ordinal = today.ordinal(); //상수의 위치값 리턴
System.out.println(ordinal);
Week day1 = Week.MONDAY;
Week day2 = Week.FRIDAY;
int result1 = day1.compareTo(day2);
int result2 = day2.compareTo(day1);
System.out.println(result1);
System.out.println(result2);
String day = "FRIDAY";
Week weekday = Week.valueOf(day);
if (weekday==Week.SATURDAY||weekday==Week.SUNDAY) {
System.out.println("주말");
}else {System.out.println("평일");}
Week[] days = Week.values();
for (Week d:days) {
System.out.println(d);
}
}
}
|
cs |
//
SUNDAY
6
-4
4
평일
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
final
: 고정값 => 값 선언 후 변경 불가
- static final
static final double PI = 3.141592;
=> 상수 이름은 주로 대문자로만
=> 메소드 밖에서 선언
6장 클래스
- 객체지향 프로그래밍
: 부품 객체들 먼저 만들고, 하나씩 조립해서 프로그램 완성
객체 : 독립적으로 존재, 서로 상호작용
메소드 : 객체 간 상호작용의 수단, 객체가 다른 객체 기능 이용하도록 함
- 객체지향 프로그래밍 특징
1. 캡슐화 : 패키징(카테고리화) => 일부 내용 내부에 감춰 사용범위 제한, 보호
2. 상속 : 상위 객체가 하위 객체에 필드, 메소드 물려줌
3. 다형성 : 같은 타입이지만 실행 결과가 다양한 객체 이용 => 하나의 타입에 여러 객체 대입 가능
ex. 타이어 - A 타입 호환 = 여러 회사의 A 타입 타이어들 모두 교체 가능
- 클래스 생성
클래스 이름 대문자로
메인 메소드 없이 생성 => run 안됨
필드, 생성자, 메서드 필요 (필드만 있어도 생성은 가능)
필드(=변수) : 객체의 정보 저장되는 곳
생성자 : 객체 생성 시 초기화
메서드 : 객체의 동작(기능, 일)
- 객체
개발자 => 클래스 설계 => 객체 인스턴스화
- 클래스 생성
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public class Account {
//은행계좌 클래스(통장)
//필드
String accountNo; //계좌번호
String ownerName; //이름
int balance;
//생성자
//메서드: 예금
void deposit (int amount) { //void : 리턴값 없음 //괄호 안: 매개변수 ex.주스 받을 컵
balance+=amount;
}
//메서드: 인출
int withdraw(int amount) { //리턴값 : int
if (balance<amount) {
return 0;
}
balance-=amount;
return amount;
}
}
|
cs |
- 객체 생성
Account chulsu; //객체 선언
chulsu= new Account(); //새 객체 생성
=>축약
Account chulsu = new Account(); //인스턴스 객체 생성
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public class AccountEx1 {
public static void main(String[] args) {
Account chulsu = new Account(); //객체(인스턴스) 선언 및 생성
chulsu.accountNo = "0101-10101-1010"; //객체 생성하면 그 필드, 메서드 모두 사용 가능
chulsu.ownerName = "김철수";
chulsu.balance = 1000;
Account gildong = new Account();
gildong.accountNo = "0202-020202-0202";
gildong.ownerName = "홍길동";
gildong.balance = 0;
chulsu.deposit(5000);
gildong.deposit(30000);
chulsu.deposit(20000);
int amount = gildong.withdraw(7000);
System.out.println("찾은 금액: "+amount);
System.out.println("잔액: "+gildong.balance);
}
}
|
cs |
※
괄호 O => 메소드
괄호 X => 필드
- 생성자 생성 (account.class)
public Account(String accNo, String ownerNa, int bal) {
accountNo=accNo;
ownerName=ownerNa;
balance=bal;
}
=>수정
public Account(String accountNo, String ownerName, int balance) {
this.accountNo=accountNo; //this=> 필드
this.ownerName=ownerName;
this.balance=balance;
}
cf. 변수 : 초기화 => int amount=4
- accountex1 에러 해결
1. 괄호 안에 초기화값 다 넣기
2. account.classs에 디폴트값 생성자 추가 ex. public Accountt(){}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public class AccountEx2 {
public static void main(String[] args) { //main : 메소드의 이름임
Account younghee = new Account("222-222-222","이영희",100);
Account chanho = new Account("111-222-3333", "박찬호" , 0);
younghee.deposit(50000);
chanho.deposit(30000);
younghee.deposit(40000);
chanho.withdraw(12000);
printAccount(younghee);
printAccount(chanho);
}//main
//통장 정보 출력 메서드 => 메소드의 분업화
static void printAccount(Account obj) { //매개변수=>Account 클래스 객체만 받음
System.out.println("계좌번호: "+obj.accountNo);
System.out.println("예금주이름: "+obj.ownerName);
System.out.println("잔액: "+obj.balance);
System.out.println("-------------------------");
}
}
|
cs |
//
계좌번호: 222-222-222
예금주이름: 이영희
잔액: 90100
-------------------------
계좌번호: 111-222-3333
예금주이름: 박찬호
잔액: 18000
-------------------------
exception (예외 처리)
발생 가능한 에러들 예측해 문구 출력 등 미리 대응하는 것
- try catch 문
public static void main(String[] args) {
try {
int num1=10;
int num2=0; //분모 0
int result = num1/num2;
System.out.println("결과 = "+result);
}catch(ArithmeticException e) {
System.out.println("0으로 나누지 마세요");
System.out.println(e.getMessage()); //에러메시지 출력
}
}
}
5장(참조) 확인문제
- 참조타입
: 배열, 열거, 클래스, 인터페이스
변수=> 스택영역, 객체=> 힙영역에 메모리 생성됨
==, != 연산자 => 객체 번지 비교 (값 그자체를 비교하는 것이 아님)
초기화값 : int 0 / String null / boolean false / double 0.0 / 배열 null (string 배열, 사용자가 만든 객체 배열?)
로컬변수 : 블록 안에 선언된 변수 => 스택 영역에 생성, 실행 블록 끝나면 소멸
정적(메소드) 영역 => 메소드코드, 상수, 열거 상수 생성됨
자바 => 메모리관리 스스로 하므로 소멸 코드 필요 X
배열, 객체 => 힙 영역에 생성됨
- String 타입
=> 클래스, 참조타입
문자열 비교 => equals 사용 (== 는 참조값 비교)
동일 문자열 리터럴 저장하는 변수 => 동일한 String 객체 참조
new String => 리터럴 같아도 또다른 객체를 생성하는 것
- 7번 문제 - 최댓값(max) 구하기
1
2
3
4
5
6
7
8
9
10
11
|
public static void main(String[] args) {
int max=0;
int[] array= {1,5,3,8,2};
for (int i=0;i<array.length;i++) {
if (array[i]>max) {
max=array[i];
}
}
System.out.println(max);
}
|
cs |
- 8번 문제 - 배열 총합, 평균 구하기
int[][] array = {
{95,86},
{83,92,96},
{78,83,93,87,88}
};
=>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public class ConfirmEx2 {
public static void main(String[] args) {
int[][] array = {
{95,86},
{83,92,96},
{78,83,93,87,88}
};
int sum=0;
double avg=0.0;
double count=0;
for (int i=0;i<array.length;i++) {
for (int j=0;j<array[i].length;j++) {
sum+=array[i][j];
count++;
}
}
System.out.println(sum);
avg= sum/count;
System.out.println(avg);
}
}
|
cs |
88.1
- 9번 문제
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
import java.util.Scanner;
public class ConfirmEx3 {
public static void main(String[] args) {
boolean run=true;
int studentNum=0;
int[] scores=null;
Scanner scanner = new Scanner(System.in);
while(run) {
System.out.println("1.학생수 2.점수입력 3.점수리스트 4.분석 5.종료");
System.out.print("선택>>");
int selectNo=scanner.nextInt();
switch(selectNo) {
case 1:
System.out.print("학생수>> ");
studentNum= scanner.nextInt();
scores = new int[studentNum];
break;
case 2:
for (int i=0;i<studentNum;i++) {
System.out.print("scores["+i+"] >> ");
scores[i] = scanner.nextInt();
}
break;
case 3:
for (int a=0;a<scores.length;a++) {
System.out.println("scores["+a+"] >> "+scores[a]);
}
break;
case 4:
int max=0;
for (int a=0;a<scores.length;a++) {
if (scores[a]>max) {
max=scores[a];
}
}
int sum=0;
for (int a=0;a<scores.length;a++) {
sum+=scores[a];
}
double avg=(double)sum/scores.length;
System.out.println(max);
System.out.println(avg);
break;
case 5:
run=false;
break;
}
}
System.out.println("프로그램 종료");
}
}
|
cs |
//
?
static, static final 차이
리턴값
생성자 this
배열 초기값 null=>String, 사용자객체 배열 / 0 =>숫자배열
static 과 static final 차이를 알려고 검색했는데 아직 이해하기 어렵다.. 책을 일단 정독해야겠음 ㅠ 이클립스 화면에서 보이는 표면적인 부분만 배우다가 힙, 스택, 2진수 등등 이론적인 부분으로 들어가니 이해하기 어려운 것 같다.. 책 정독하고말거야
음.. 초기에는 한 개념에 온갖 예시들이 너무 많아서 기본 문법, 예시 하나 정도만 앞에 추가하고 뒤에 다 몰아넣으려고 했는데 그게 더 복잡하게 만드는 거 같아서 그냥 상위 카테고리 하나 만들면 다 때려넣어야겟다
'Programming > 국비학원' 카테고리의 다른 글
220503 - 6장 클래스 확인문제, 상속(extends), 오버라이딩(재정의) (0) | 2022.05.04 |
---|---|
220502 - throw, 다른 생성자 호출, 메소드 오버로딩, 캡슐화(private), getter와 setter, static final, 매개변수 수 모를 경우, 정적 필드와 메소드, 싱글톤, import문, 접근제한자 (0) | 2022.05.03 |
220428 - 배열 복사, 열거 타입 (0) | 2022.04.29 |
220429 - 버전 관리 - CLI, GUI (0) | 2022.04.29 |
220427 - github, 이것이 자바다 1 복습 (0) | 2022.04.28 |