thesunset 2022. 9. 25. 13:55

# MethodTest1

package com.kh.chap06.controller;

//controller : 기능

public class MethodTest1 {

//클래스 안에 있어서 메소드라는 이름.

//다른 곳에서는 함수라고 부름. 본질은 함수와 같음

/*

* 메소드(Method) : 입력을 가지고 어떤 일을 수행한 다음에 결과물을 내놓음.

*

* [표현법]

* 접근제한자 (예약어) **반환형** 메소드식별자(매개변수의자료형 매개변수식별자=> 입력값) {

*

* 수행할 코드;

*

* return 반환값;//결과값

* }

* 생략가능한 것: 예약어, 매개변수, return문 부분(반환형이 void일 경우)

*

* 반환형: 반환할 값의 자료형

* 호출할 때 인자값 => 매개변수의 자료형과 갯수가 일치해야함 반드시 **********

* == 메소드 호출할 때 전달하려는 자료형과 매개변수의 자료형이 같아야 에러가 안남

*

* 한 번 정의해두고 필요할 때마다 호출 사용 언제든!

*

*/

//1. 매개변수도 없고 반환값도 없는 메소드

public void method1() {

System.out.println("매개변수와 반환값이 둘 다 없는 메소드입니다.");

int sum = 0;

for(int i = 1; i<=10; i++ ) {

sum += i; //sum = sum + i

}

System.out.println(sum);

//return; -> 자동 생략

//void일 경우 return이 생략 JVM이 자동으로 만들어줌.

}

//2. 매개변수는 없고 반환값은 있는 메소드

public int method2() {

System.out.println("매개변수는 없고 반환값은 있는 메소드입니다.");

//1에서부터 100까지의 랜덥값을 발생시켜셔 돌려주고 싶다.

return (int)(Math.random() * 100) + 1;

}

//3. 매개변수는 있고 반환값은 없는 메소드

public void method3(int num1, int num2) {//내가 받고 싶은 변수, 개수 //나를 부르려면 정수 2개를 줘라는 뜻

System.out.println("매개변수는 있고 반환값은 없는 메소드입니다.");

int min = 0;

int max = 0;

if(num1 < num2) {//mum1이 num2보다 작니?(의문문)

//네

min = num1;

max = num2;

} else {

//아니요

max = num1;

min = num2;

}

System.out.println("최소값: " + min + ", 최대값: " + max);

}

//4. 매개변수도 있고 반환값도 있는 메소드

public int method4(int a, int b) { //마지막 리턴 자료형을 모르겠을 땐 void로 적고 돌려줄 값을 알았을 때 수정

System.out.println("매개변수도 있고 반환값도 있는 메소드입니다.");

//int sum = a + b;

return a + b;

}

//4가지의 가장 큰 차이: 출력문의 위치

/*

* 반환형이 없는 메소드 : 출력문을 작성하는 편

* 반환형이 있는 메소드 : 출력문을 호출하는 부분에 출력문을 작성함.

*

*/

}


# MethodTest2

package com.kh.chap06.controller;

public class MethodTest2 {

//static 메소드 만들기

//1.

public static void method1() { //프로그램 실행시 static영역에 올라감

System.out.println("매개변수랑 반환값이 둘 다 없는 메소드 입니다.");

}

//2.

public static String method2() {

return "매개변수는 없지만 반환값은 있는 메소드 입니다.";

}

//3.

public static void method3(String name, int age) {

System.out.println("매개변수는 있고 반환값은 없는 메소드입니다.");

System.out.println("출력구문: " + name + "님 " + age + "살 입니다. ");

}

//4.

public static String method4(String name, int age) {

return name + "님 안녕하세요. " + age + "살 이시네요.";

}

}


# OverloadingTest

package com.kh.chap06.controller;

public class OverloadingTest {

/*

* 메소드 오버로딩

*

* - **한 클래스 안에** 같은 메소드 으로 여러 메소드들을 정의 할 수 있는 방법

* - 매개변수의 자료형의 개수, 순서, 종류 다 다르게 작성해야 함

* - 단, 매개변수명, 접근제한자, 반환형은 메소드 오버로딩에 영향을 주지 않는다.

*

*/

//메소드 이름은 test로 통일

public void test() {

System.out.println("안녕하세요");

System.out.println("오늘 수업 6시간 남았어요.");

}

public void test(int a) { //동적바인딩: 실행 시 동적으로 맞는 메소드를 실행시켜줌.

System.out.println("이건 int a하나만 받았어요.");

}

public void test(int a, String s) {

System.out.println("이건 int a-먼저 String s-두 번째로 받았어요.");

}

public void test(String s, int a) {

System.out.println("이건 String s-먼저 int a-두 번째로 받았어요.");

}

public void test(int a, int b) {

System.out.println("int a, int b 받았어요.");

}

//메소드명은 모두 동일한데, 메소드 호출 시 인자값을 어떻게 전달하느냐에 따라 똑같은 이름으로 여러개의 메소드를 표현할 수 있음.

/*

* public void test(int c, int b){

* System.out.println("이건 int c, int b 받았어요."

* }

* - 정수형 두 개를 받는 test를 하나 더 만든다면?

* 매개변수의 이름이랑은 상관없이 자료형의 개수, 순서가 같기 때문에 에러가 발생함

* - 즉, 매개변수의 자료형의 개수와 순서가 항상 다르게 작성해야 한다.

*

*/

/*

public void test(int a, int b, String s) {

System.out.println("int a int b String s");

}

public int test (int a, int b, String s) {

}

반환형이 다르다고 오버로딩이 적용되지 않는다.

메소드를 호출하는 시점에서 매개변수가 동일하면 무조건 에러가 발생

반환형과 상관없이 매개변수의 자료형의 개수와 순서가 다르게 작성되어야 함.

*/

/*

private void test(int a, int b, String s) {

}

접근제한자가 다르다고 오버로딩이 적용되지 않음.

접근제한자와는 상관없이 매개변수의 자료형의 개수와 순서는 다르게 작성되어야 함

*/

}


# MethodTest 1, 2 OverloadingTest_Run

package com.kh.chap06.run;

import com.kh.chap06.controller.MethodTest1;

import com.kh.chap06.controller.MethodTest2;

import com.kh.chap06.controller.OverloadingTest;

public class Run {

public static void main(String[] args) {

//객체 생성(stack-주소값) //heap에 공간 할당

/*

MethodTest1 mt1 = new MethodTest1(); //메모리에 할당

mt1.method1();//mt1에 접근해 메소드 호출

int a = mt1.method2(); //1~100사이의 정수'값' => 재사용하고 싶으면 변수선언 해 대입해주기. 값을 얻어내기위해서

System.out.println("랜덤값: " + a);

System.out.println("랜덤값: " + mt1.method2()); //=> 재사용을 안해도 되면 값 그자체를 출력 //호출한 메소드로 가서 시작점부터 진행

mt1.method3(1, 10);// 정수 2개 입력

int b = mt1.method4(5, 3);

System.out.println(b);

*/

//Math.random()

//Math mt = new Math(); XXXX

//Math클래스 안에 내용들은 모두 static영역에 올라가 있어서 heap에 생성할 필요가 없음

//static : 객체를 생성하지 않아도 호출 가능 ( new 안 해도 됨!)

//[표현법] 클래스이름.메소드이름(); ex)Math.random();

/*

MethodTest2.method1(); //이탤릭체로 써짐.

//String a = MethodTest2.method2();

System.out.println(MethodTest2.method2());

MethodTest2.method3("홍길동", 21);

System.out.println(MethodTest2.method4("홍길동", 21));

*/

OverloadingTest ot = new OverloadingTest();

ot.test();

ot.test(2);

ot.test(3, "v");

ot.test("v",3 );

ot.test(2, 3);

}

}


# Book

package com.kh.chap01.model.vo;

public class Book {

//필드부

private String title;

private String publisher;

private String author;

private int price;

private double discountRate;

//생성자부

public Book(){}

public Book(String title, String publisher, String author) {

this.title = title;

this.publisher = publisher;

this.author = author;

} // 오버로딩 적용 객체 생성과 동시에 필드에 초기화

public Book(String title, String publisher, String author, int price, double discountRate) {

this.title = title;

this.publisher = publisher;

this.author = author;

this.price = price;

this.discountRate = discountRate;

}

//매소드부

public void setTitle(String title) {

this.title = title;

}

public void setPublisher(String publisher) {

this.publisher = publisher;

}

public void setAuthor(String author) {

this.author = author;

}

public void setPrice(int price) {

this.price = price;

}

public void setDiscoutRate(double discountRate) {

this.discountRate = discountRate;

}

public String getTitle() {

return title;

}

public String getPublisher() {

return publisher;

}

public String getAuthor() {

return author;

}

public int getPrice() {

return price;

}

public double getDiscountRate() {

return discountRate;

}

public String information() {

return "책의 이름은" + title + " 출판사는 " + publisher + " 작가는 " + author + " 가격은 " + price + " 할인율은 " + discountRate + "입니다.";

}

}


# ObjectRun

package com.kh.chap01.run;

import java.util.Scanner;

import com.kh.chap01.model.vo.Book;

public class ObjectRun {

public static void main(String[] args) {

Book b1 = new Book(); //인스턴스화

System.out.println(b1.information()); // null null null 0 0.0

Book b2 = new Book("해리포터", "영국의 어디", "조앤K롤링");

System.out.println(b2.information());

Book b3 = new Book("자바의 정석", "자바출판사", "남궁성", 15000, 0.1);

System.out.println(b3.information());

//도서 정보를 입력받아서 도서들의 정보를 출력해주는 프로그램

//책 3권의 정보를 입력받겠다고 가정할 것.

//입력은 스캐너 사용

//객체를 따로따로 관리

b1 = null;

b2 = null;

b3 = null;

-> 앞의 값 연결 끊어주기

Scanner sc = new Scanner(System.in);

// 입력 받을 정보: 도서명, 출판사, 저자, 가격, 할인률

//nextLine사용시 반복문 사용 시 에러 > sc.nextLine()을 한 번 더 입력 해줌

for(int i = 0; i<3; i++) {

System.out.println("책 제목은 무엇인가요?");

String title = sc.nextLine();

System.out.println("책 출판사는 어디인가요?");

String publisher = sc.nextLine();

System.out.println("책의 저자는 어디인가요?");

String author = sc.nextLine();

System.out.println("책의 가격은 얼마인가요?");

int price = sc.nextInt();

System.out.println("책의 할인율은 얼마인가요?");

double discountRate = sc.nextDouble();

sc.nextLine();

if(i==0) {

b1 = new Book(title, publisher, author, price, discountRate);

} else if(i==1) {

b2 = new Book(title, publisher, author, price, discountRate);

} else { b3 = new Book(title, publisher, author, price, discountRate);

}

}

System.out.println(b1.information());

System.out.println(b2.information());

System.out.println(b3.information());

/*

for(int i = 1; i<=3; i++) {

System.out.println(bi.information());

} => 에러남

*/

// 사용자로부터 검색할 도서의 제목을 입력받아서

// 각 전체 도서들의 제목과 하나하나 비교해서 일치하는 도서의 가격을 알려주는 프로그램

System.out.println("검색할 도서 제목을 입력해주세요.>");

String www = sc.nextLine();

if(www.equals(b1.getTitle())) {

System.out.println(b1.getPrice());

}

if(www.equals(b2.getTitle())) {

System.out.println(b2.getPrice());

}

if(www.equals(b3.getTitle())) {

System.out.println(b3.getTitle());

}

/*

for(int i = 1; i<3; i++){

if(www.equals(bi.getTitle())) {

System.out.println(bi.getPrice());

-> 안됨 에러남

}

}

*/

}

}


=> 반복문을 사용하고 싶다면?객체배열 사용하기

# ObjectArrayRun

package com.kh.chap01.run;

import java.util.Scanner;

import com.kh.chap01.model.vo.Book;

public class ObjectArrayRun {

public static void main(String[] args) {

// 배열의 특징

// 참조형

// 인덱스는 0번부터

// 순서대로 저장된다.

// ☆같은 자료형끼리만 묶을 수 있음★

//int[] iArr = new int[5]; => iArr정수형 배열 5칸짜리

//String[] sArr = new String[5]; => sArr문자열형 배열 5칸짜리

//Book[] bArr = new Book[3]

//=> 객체 배열

//객체배열의 선언 및 할당

//[표현법]

//클래스이름[] 배열이름 = new 클래스이름[배열크기];

Book[] arr = new Book[3]; // arr[0], arr[1]. arr[2]

Scanner sc = new Scanner(System.in);

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

System.out.println("제목> ");

String title = sc.nextLine();

System.out.println("출판사> ");

String publisher = sc.nextLine();

System.out.println("저자> ");

String author = sc.nextLine();

System.out.println("가격> ");

int price = sc.nextInt();

System.out.println("할인율> ");

double discountRate = sc.nextDouble();

sc.nextLine();

arr[i] = new Book(title, publisher, author, price, discountRate);//주소값.

}

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

System.out.println(arr[i].information());

}

System.out.println("검색할 책 제목> ");

String searchTitle = sc.nextLine();

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

if(arr[i].getTitle().equals(searchTitle)) {

System.out.println(arr[i].getPrice());

}

}

}

}


#Phone

package com.kh.chap02.model.vo;

public class Phone {

//필드부

//이름 시리즈 브랜드 가격

private String name;

private String series;

private String brand;

private int price;

//생성자부

//기본생성자

//모든 필드에 대한 매개변수 생성자

public Phone() {}

public Phone(String name, String series, String brand, int price ) {

this.name = name;

this.series = series;

this.brand = brand;

this.price = price;

}

//메소드부

//getter,setter,information

public void setName(String name) {//전달받음, 돌려줄 필요 없음(반환형x)

this.name = name;

}

public String getName() { //돌려줘야함(반환형)

return name;

}

public void setSeries(String series) {

this.series = series;

}

public String getSeries() {

return series;

}

public void setBrand(String brand) {

this.brand = brand;

}

public String getBrand() {

return brand;

}

public void setPrice(int price) {

this.price = price;

}

public int getPrice() {

return price;

}

public String information() {

return name + "의 시리즈는 " + series + "이고," + brand + "의 브랜드이며, 가격은 " + price + "원 입니다.";

}

}


#Phone_ObjectArrayRun

package com.kh.chap02.run;

import java.util.ArrayList;

import com.kh.chap02.model.vo.Phone;

public class ObjectArrayRun {

public static void main(String[] args) {

//int[] arr = new int[3]

//객체 배열 선언 및 할당

Phone[] arr = new Phone[3];

System.out.println(arr);//arr에는 주소값이 들어있음.

System.out.println(arr.length);//정수 3

System.out.println(arr[0]); //참조형의 기본값 null

arr[0] = new Phone();

System.out.println(arr[0]); //주소값

arr[0].setName("아이폰");

arr[0].setSeries("13");

arr[0].setBrand("애플");

arr[0].setPrice(1300000);

System.out.println(arr[0]); //주소값

System.out.println(arr[0].information());

arr[1] = new Phone("갤럭시", "Z4", "삼성", 1400000);

arr[2] = new Phone("픽셀", "123", "Google", 900000);

// 총합계 가격, 평균가 출력

int sum = 0;

int avg = 0;

//sum = arr[0].getPrice() + arr[1].getPrice() + arr[2].getPrice();

//avg = sum/3;

//=> 유지보수가 어려움

//System.out.println("합계: " + sum + " 평균: " + avg);

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

sum += arr[i].getPrice();

avg = sum/arr.length;

}

System.out.println("합계: " + sum + " 평균: " + avg);

//ArrayList 버전 - 자바 마지막에 배움

ArrayList<Phone> list = new ArrayList(3);

list.add(new Phone("아이폰", "13", "Apple", 1300000));

list.add(new Phone("갤럭시", "Z4", "삼성", 1500000));

list.add(new Phone("픽셀", "123", "Google", 1100000));

int sum2 = 0;

//~~

}

}


# Cat

package com.kh.exam.model.vo;

public class Cat {

public static final String STORE = "승철가게"; //상수 필드

private String name;

public Cat() { }

public Cat(String name) {

this.name = name;

}

public void setName(String name) {

this.name = name;

}

public String getName() {

return name;

}

public String getStore() {

return STORE; //setter는 이미 고정되어있어 바뀌지 않으므로 하지 않고 getter만

}

public void info() {

System.out.println( STORE + "에 살고있는 " + name + "이(가) 있습니다.");

}

}


# Dog

package com.kh.exam.model.vo;

public class Dog {

private String name;

private double weight;

private double height;

public Dog() { }

public Dog(String name, double weight, double height) {

this.name = name;

this.weight = weight;

this.height = height;

}

public void setName(String name) {

this.name = name;

}

public String getName() {

return name;

}

public void setWeight(double weight) {

this.weight = weight;

}

public double getWeight() {

return weight;

}

public void setHeight(double height) {

this.height = height;

}

public double getHeight() {

return height;

}

public void info() {

System.out.println(name + "은(는) 몸무게는 " + weight + "kg 이고, 몸의 길이는 " + height + "cm 입니다.");

}

}


#Test(Cat, Dog Run)

package com.kh.controller;

import com.kh.exam.model.vo.Cat;

import com.kh.exam.model.vo.Dog;

//== import com.kh.exam.model.vo.*; == 모두 import 하고 싶을 때

public class Test {

public static void main(String[] args) {

Cat[] carr = new Cat[3];

carr[0] = new Cat(); //반드시 공간 할당 ** (stack빼고)

carr[0].setName("냐옹이");

carr[1] = new Cat();

carr[1].setName("까옹이");

carr[2] = new Cat("댜옹이");

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

carr[i].info();

}

Dog[] darr = new Dog[2];

darr[0] = new Dog("복실이",3.4,50);

darr[1] = new Dog("허스키", 10.3, 130.4);

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

darr[i].info();

}

System.out.println(darr[0].getName() + "이의 몸길이는 " + darr[0].getHeight());

//부분만 출력할 수 있음.

}

}