본문 바로가기
수업노트

23.03.16

by MIniLabo 2023. 3. 16.

o constructor

//생성자 함수

//클래스명과 동일한 함수

//오버로딩 가능

//new 연산자와 함께 메모리 할당시에 사용

//※School 클래스 생성후 테스트~

--------------------------------------------------------------------------

class School { //public 생략되면 현 패키지 내에서만 사용가능

//멤버변수 field column property attribute

//멤버변수 private로 막아두는 이유는 함수를 통해서만 접근하라고

private String name;

private int kor, eng, mat;

private int aver;

 

//생성자 함수

public School() {

System.out.println("School() 호출됨");

} //end 자동생성됨

 

//생성자함수도 오버로드(함수명 중복 정의)가 가능

 

public School(String n) {

name = n;

}//end

 

public School(int k, int e, int m) {

kor = k;

eng = e;

mat = m;

}//end

 

public School(String n, int k, int e, int m) {

name = n;

kor = k;

eng = e;

mat = m;

}

 

//멤버함수

void calc() {//현 패키지에서만 사용가능

aver = (kor + eng + mat)/3;

}//calc() end

 

public void disp() {

System.out.println(name);

System.out.println(kor);

System.out.println(eng);

System.out.println(mat);

System.out.println(aver);

}//disp() end

}//class end

---------------------------------------------------------

//new School();

 

//생성자 함수의 전달값은 객체선언과 동시에 초기값을 전달해 주는 역할을 한다

School one = new School("개나리");

one.calc();

one.disp();

 

School two = new School(70, 80, 90);

two.calc();

two.disp();//null, 70,80,90,80

 

School three = new School("진달래", 10, 20, 30);

three.calc();

three.disp();

===================================================

o String

public class Test02_String {

public static void main(String[] args) {

// 문자열 관련 클래스

 

//아래의 둘은 동일형식, 그러나 둘의 주소는 다름

String str = "HAPPY";

String name = new String("HAPPY");

 

if(str == name) {

System.out.println("같다");

}else {

System.out.println("다르다");

}//if end, str과 name의 주소가 다르기 때문에 "다르다" 출력

//따라서 문자열 데이터는 내용비교 시 ==연산자 사용하면 안됨

//equals()함수 이용할 것

if(str.equals(name)) {//name변수의 내용과 같나?

System.out.println("같다");

}else {

System.out.println("다르다");

}//if end, 내용이 같으므로 "같다"출력

 

//문자열의 개수가 0인지 확인하는 함수

if(str.isEmpty()) {

System.out.println("빈문자열이다");

}else {

System.out.println("빈문자열 아니다");

}//if end

 

//특정 문자를 기준으로 문자열 분리하기

//이하는 공백 기준으로 문자열 분리

str = new String("Gone With The Wind");

String[] word = str.split(" ");//리턴형이 String 배열이므로

for(int i = 0; i < word.length; i++) {

System.out.println(word[i]);

}//for end

 

//////////////////////

 

//문자열에서 공백문자를 기준으로 분리하기

StringTokenizer st = new StringTokenizer(str, "i");

while(st.hasMoreElements()) {//토큰할 문자가 있는지 계속 물어봄

System.out.println(st.nextToken());//토큰할 문자열 가져오기

}//while end

 

////////////////////////////////////////

 

//문자열 연산 속도

//String < StringBuffer < StringBuilder

 

String s1 = "";

System.out.println(s1.length());//0

 

s1 = s1 + "ONE";

System.out.println(s1.length());//3

 

s1 = s1 + "TWO";

System.out.println(s1.length());//6

 

s1 = s1 + "THREE";

System.out.println(s1.length());//11

System.out.println(s1);//ONETWOTHREE

 

//모든 문자열 지우기(빈 문자열 대입)

s1 = "";

System.out.println(s1.length());//0

System.out.println("#" + s1 + "#");//

///////////////////////////////////////

 

 

StringBuilder s2 = new StringBuilder();

 

s2.append("SEOUL");

System.out.println(s2.length() + s2.toString());

 

s2.append("JEJU");

System.out.println(s2.length() + s2.toString());

 

s2.append("BUSAN");

System.out.println(s2.length() + s2.toString());

 

 

//모든 문자열 지우기

s2.delete(0, s2.length());//s2의 문자열 0번째부터 끝까지 지우기

System.out.println(s2.length());//0

 

 

StringBuffer s3 = null;

//NullPointerException 발생

System.out.println(s3.length());

//예외, 메모리에 할당되지 않았으므로 길이 알 수 없음

 

}//main() end

===========================================

o 연습문제

public class Test03_quiz {

public static void main(String[] args) {

// String 관련 연습문제

//문1) 이메일 주소에 @문자 있으면

// @글자 기준으로 문자열을 분리해서 출력하고

// @문자 없다면 "이메일주소 틀림" 메세지를 출력하시오

/*

출력결과

webmaster

itwill.co.kr

*/

 

String email = new String("webmaster@itwill.co.kr");

 

if(email.indexOf("@") == -1) {//해당 문자 없으면 -1출력하는 메서드

System.out.println("이메일주소 틀림");

}else {

System.out.println("이메일주소 맞음");

}

 

int pos = email.indexOf("@");

System.out.println(pos);//9

 

//substring(). split(), StringTokenizer() 등 사용

 

String id1 = email.substring(0, pos);//0, (9-1)

String server = email.substring(pos+1);//10번째부터 마지막까지

 

System.out.println("모범답안");

System.out.println(id1);

System.out.println(server);

System.out.println("---------------");

 

//내가한것 성공(이메일주소형식 맞는지 확인하는 것은 누락)

//(1) .split으로 분리

System.out.println("(1) .split으로 분리");

 

String [] em1 = email.split("@");

for(int a = 0; a < em1.length; a++) {

System.out.println(em1[a]);

}

 

System.out.println("---------------");

 

 

//(2)StringTokenizer으로 분리

System.out.println("(2)StringTokenizer으로 분리");

 

StringTokenizer em2 = new StringTokenizer(email, "@");

while(em2.hasMoreTokens()) {

System.out.println(em2.nextToken());

}

 

System.out.println("---------------");

 

//////////////////////////////////

 

//문2) 이미지 파일(.png, jpg, gif)만 첨부할 수 있는 포토갤러리 게시판

/*

* 출력결과

파일명 : sky2023.03.16

확장명 : jpg

*/

 

String path = new String("i:/frontend/images/sky2023.03.16.jpg");

 

//모범답안

System.out.println("모범답안");

 

//path에서 마지막 "/" 기호의 순서값

int lastSlash = path.lastIndexOf("/");

System.out.println(lastSlash);//18

 

//전체 파일명

String file = path.substring(lastSlash + 1);

System.out.println("전체 파일명 : " + file);

 

//file에서 마지막 "." 기호의 순서값

int lastDot = file.lastIndexOf(".");

System.out.println(lastDot);//13

 

//파일명

String filename = file.substring(0, lastDot);

System.out.println("파일명 : " + filename);

 

//확장명

String ext1 = file.substring(lastDot+1);

System.out.println("확장명 : " + ext1);

 

//확장명을 전부 소문자로 치환

ext1 = ext1.toLowerCase();

if(ext1.equals("png") ||ext1.equals("jpg") ||ext1.equals("gif")) {

System.out.println("파일이 전송되었습니다.");

}else {

System.out.println("이미지 파일만 가능합니다");

}//if end

 

System.out.println("---------------------");

System.out.println("내가한것, 성공");

//내가한것, 성공

int idnum = path.lastIndexOf("/");

//뒤에서부터 찾아올때 해당 문자열(/) 순서

//경로제외한 파일명 시작되는 문자열 순서

System.out.println(idnum);//18

 

int extnum = path.lastIndexOf(".");

//뒤에서부터 찾아올때 해당 문자열 순서

//->확장명 시작되는 문자열 순서(. 포함)

System.out.println(extnum);//32

 

 

String id = path.substring(idnum+1, extnum);

// 슬래시 다음글자부터 확장명(.jpg)이전까지 자르기

System.out.println("파일명 : " + id);

//파일명출력, 파일명 : sky2023.03.16

 

 

//System.out.println(path.length());

//35 전체 (경로명+파일명+확장명)길이

 

int size = path.length();

String ext = path.substring(extnum+1, size);

System.out.println("확장명 : " + ext);//확장명출력, 확장명 : jpg

}//main() end

=================================================

o this

//클래스가 자신을 가리키는 대명사

//일반지역변수와 멤버변수를 구분하기 위함

//※Score 클래스 생성후 테스트~

class Score {

 

private String name = "손흥민";

private int kor, eng, mat;

private int aver;

 

//생성자함수 constructor

//생성자함수를 오버로드하면 기본생성자함수는 자동으로 생성되지 않음

//따라서 그냥 항상 기본 생성자 함수 수동으로 생성할 것을 추천

public Score() {}

 

public Score(String name, int kor, int eng, int mat) {

//여기서의 name은 멤버변수인가 지역변수인가?>>구분하기 어려움

//변수명은 통일하는 것이 좋음

//여기서 name의 우선순위는 지역변수

//this.멤버변수=지역변수

this.name = name;

this.kor = kor;

this.eng = eng;

this.mat = mat;

this.aver = (kor+eng+mat)/3;

}//end

 

//멤버함수 method

public void disp() {

//지역변수의 우선순위가 가장 높다

String name = "박지성";

System.out.println(name);

//멤버변수인 손흥민이 아닌 지역변수인 박지성이 출력

 

System.out.println(this.name);//손흥민

System.out.println(this.kor);

System.out.println(this.eng);

System.out.println(this.mat);

System.out.println(this.aver);

 

}//disp() end

 

}//class end

---------------------------------------------------

public static void main(String[] args) {

// this

//클래스가 자신을 가리키는 대명사

//일반지역변수와 멤버변수를 구분하기 위함

 

Score one = new Score();

one.disp();

 

Score two = new Score("김연아", 50,60,70);

two.disp();

 

Score three = new Score("무궁화", 10,20,30);

three.disp();

 

//객체가 참조하고 있는 주소

System.out.println(one.hashCode());

System.out.println(two.hashCode());

System.out.println(three.hashCode());

////////////////////////////////////////////

 

Score kim = new Score("봉선화", 10,20,30); //#100

Score lee = new Score("라일락", 40,50,60); //#200

Score park = new Score("진달래", 70,80,90);//#300

 

//변수 : 지역변수, 전역변수, 매개변수, 참조변수

 

//객체 배열(클래스도 배열 가능)

Score[] score = {

new Score("오필승", 11,22,33)

,new Score("코리아", 44,55,66)

,new Score("대한민국", 77,88,99)

};

/*

+---------+---------+--------+

| #100 | #200 | #300 |

+---------+---------+--------+

score[0] score[1] score[2]

*/

System.out.println("----------");

score[0].disp();//"박지성", "오필승", 11,22,33,22

score[1].disp();//"박지성", "코리아", 44,55,66,55

score[2].disp();//"박지성", "대한민국", 77,88,99,88

}//main() end

 

============================================

o static

//Sawon클래스를 생성하고 실습하기

class Sawon {

 

//멤버변수 field

String sabun; //사원번호,변수 앞 package 생략됨

String name; //이름

int pay; //급여

 

 

//생성자함수 constructor

public Sawon() {}

public Sawon(String sabun, String name, int pay) {

this.sabun = sabun;

this.name = name;

this.pay = pay;

}

 

//static 변수, 일반변수와 구분하기 위해 모두 대문자로 쓰는 경우 많음

static String COMPANY = "(주)아이티윌";

static int SUDANG = 10;

static double TAX = 0.03;

 

 

//static 함수

static void line() {

System.out.println("=================");

}//정적함수 line() end

 

}//class end

------------------------------------------------------------------------------------------

public static void main(String[] args) {

// static 정적

//->변수(정적변수, 클래스변수), 함수

//->메모리 생성 한번만, 소멸도 1번만

//->new연산자 이용해서 별도의 객체 생성 없이 사용가능

 

//static은 클래스명으로 직접 접근 가능

//->클래스명.변수

//->클래스명.함수()

//스태틱이 붙은 함수는 별도의 선언 없이 바로 사용 가능

//즉, Math math = new Math();를 안해도됨

 

/*

System.out.println(Math.PI);//클래스명.변수 -> 바로 사용가능

System.out.println(Math.abs(-3));//클래스명.함수

System.out.println(String.format("%.2f", 12.3456));

*/

///////////////////////////////////////

 

//Sawon클래스를 생성하고 실습하기

 

//static변수와 static함수는 클래스명으로 직접 접근한다

System.out.println(Sawon.COMPANY);

System.out.println(Sawon.SUDANG);

System.out.println(Sawon.TAX);

Sawon.line();

//////////////////////////////////

 

//1) static의 특징을 적용하지 않았을 때(비추)

Sawon one = new Sawon("1001", "개나리", 100);

//나의 세금

double myTax = one.pay*one.TAX;

 

//나의 총 지급액 = 급여-세금+수당

int total = (int)(one.pay - myTax + one.SUDANG);//100-3+10

 

System.out.println("회사 : " + one.COMPANY);

System.out.println("사번 : " + one.sabun);

System.out.println("이름 : " + one.name);

System.out.println("급여 : " + one.pay);

System.out.println("수당 : " + one.SUDANG);

System.out.println("세금 : " + myTax);

System.out.println("총지급액 : " + total);

one.line();

 

 

 

//2) static의 특징을 적용한 경우(추천)

Sawon two = new Sawon("1002", "진달래", 200);

myTax = two.pay * Sawon.TAX;

total = (int)(two.pay - myTax + Sawon.SUDANG);

System.out.println("회사 : " + Sawon.COMPANY);

System.out.println("사번 : " + two.sabun);

System.out.println("이름 : " + two.name);

System.out.println("급여 : " + two.pay);

System.out.println("수당 : " + Sawon.SUDANG);

System.out.println("세금 : " + myTax);

System.out.println("총지급액 : " + total);

Sawon.line();

//////////////////////////////////////////////

 

//3) static 변수의 연산(continue)

//->생성도 1번, 소멸도 1번

 

Sawon kim = new Sawon("1003", "무궁화", 300);

Sawon lee = new Sawon("1004", "봉선화", 400);

 

System.out.println(kim.SUDANG);//10

System.out.println(lee.SUDANG);//10

 

kim.SUDANG = kim.SUDANG + 1;//10+1=11

System.out.println(kim.SUDANG);

 

 

lee.SUDANG = lee.SUDANG+1;//11+1

System.out.println(lee.SUDANG);

 

 

Sawon.SUDANG = Sawon.SUDANG+1;//12+1, 하나의 변수이므로 계속 연산이 누적됨

 

System.out.println(Sawon.SUDANG);//추천, 13

System.out.println(kim.SUDANG);//13

System.out.println(lee.SUDANG);//13

 

}//main() end

'수업노트' 카테고리의 다른 글

23.3.20  (0) 2023.03.20
23.3.17  (0) 2023.03.17
23.3.15  (0) 2023.03.15
23.3.14  (1) 2023.03.14
23.3.13  (0) 2023.03.13