반응형

 

클래스

 

: 필드, 생성자,  메소드의 세가지로 구성된다.

 

필드 : 객체의 데이터가 저장되는 곳

 

생성자 : 객체 생성 시 초기화 역할 담당

 

메소드: 객체의 동작에 해당하는 실행 블록

 

 

필드, 생성자, 메소드 예시

 

 

 

필드 예시

 

 

package kr.or.ddit.study06.sec02;

// 필드 : 데이터를 저장하는 공간을 만듦.
public class TV {
	String company;
	String name;
	int year;
}

 

package kr.or.ddit.study06.sec02;

public class TvExample {
	public static void main(String[] args) {
		// 힙 메모리에 값이 저장됨.
		TV tv = new TV(); // tv에는 주소값이 저장되어 있음.
		tv.company = "삼성";
		tv.name = "컬러 Tv";
		tv.year = 2023;
		
		TV tv2 = new TV();
		tv2.company = "LG";
		tv2.name = "OLED TV";
		tv2.year = 2023;
		
		System.out.println("tv1 : " + tv.company + ", "
									+ tv.name + ", " 
									+ tv.year);
		
		System.out.println("tv2 : " + tv2.company + ", "
				+ tv2.name + ", " 
				+ tv2.year);
	}
}

 

결과 화면1

 

 

package kr.or.ddit.study06.sec02;

public class Student {
	/*
	 * 학과  major
	 * 이름  name
	 * 나이  age
	 * 키     key
	 */
	
	// static은 상태를 공유하는 변수 static을 추가할 시 하나만 변경하면 다른 것도 전체적으로 바뀜.
	// class에는 staic이라는 값이 단 하나만 존재함. => 저장공간을 따로 만들어서 그곳을 가리킴.
	// static : 멤버변수
	static int year = 2023;
	String group = "402호";
	String major;
	String name;
	int age;
	double key;
	
	// alt + shift + s > Generate toString > Generate 선택
	@Override
	public String toString() {
		return "학생 : year=" + year + ", group=" + group + ", major=" + major + ", name=" + name + ", age=" + age
				+ ", key=" + key;
	}
}

 

package kr.or.ddit.study06.sec02;

public class StudentExample {
	public static void main(String[] args) {
		/*
		 * 학생 2명 만드록 각각 값 저장, 출력 해보기
		 */
		
		Student student1 = new Student();
		student1.major = "수학과";
		student1.name = "정제문";
		student1.age = 20;
		student1.key = 180;
		
		Student student2 = new Student();
		student2.major = "철학과";
		student2.name = "임재욱";
		student2.age = 21;
		student2.key = 180;
		
		
//		System.out.println("학생1 : " + student1.group + ", \t"
//									+ student1.major + ",\t"
//									+ student1.name + ", \t"
//									+ student1.age + ", \t"
//									+ student1.key );
//		System.out.println("학생2 : " + student2.group + ", \t"
//									+ student2.major + ",\t"
//									+ student2.name + ", \t"
//									+ student2.age + ", \t"
//									+ student2.key );
		
		student1.year = 2024;
		
		// 한번에 전체 출력할 때
		System.out.println(student1);
		System.out.println(student2);
	}
}

 

결과 화면1

 

 

다른 클래스에서도 불러올 수 있다. 굳이 AnimalExample에서만 불러오지 않아도 된다.

 

package kr.or.ddit.study06.sec02;

public class Animal {
	/*
	 * 이름			: name
	 * 포유류/조류 등등	: type
	 * 평균 수명		: life
	 * 평균 무게		: kg
	 */
	
	String name;
	String type;
	double life;
	double kg;
	
	@Override
	public String toString() {
		return "Animal [name=" + name + ", type=" + type + ", life=" + life + ", kg=" + kg + "]";
	}
	
}

 

package kr.or.ddit.study06.sec02;

public class AnimalExample {
	public static void main(String[] args) {
		Animal a1 = new Animal();
		
		a1.name = "a1";
		a1.type = "포유류";
		a1.life = 10;
		a1.kg = 10;
		
		System.out.println(a1);
	}
}

 

결과 화면2

 

 

package kr.or.ddit.study06.sec02;

public class Score {
	/*
	 * 학생이름	name
	 * 	    국어
	 * 	    영어
	 * 	    수학
	 * 	    총점
	 * 	    평균
	 * 	    등수
	 */
	
	// 필드값
	// main 메소드 안에 넣을 시 다른 곳에서 불러오지 못함. => 꼭 class에 있어야 함.
	static String group = "404호";
	String name;
	int kor;
	int eng;
	int math;
	int sum;
	double avg;
	int rank;
	
	@Override
	public String toString() {
		return "Score [name=" + name + ", kor=" + kor + ", eng=" + eng + ", math=" + math + ", sum=" + sum + ", avg="
				+ avg + ", rank=" + rank + "]";
	}
	
}

 

package kr.or.ddit.study06.sec02;

public class ScoreExample {
	public static void main(String[] args) {
		Score s1 = new Score();
		s1.name = "홍길동";
		s1.kor = 100;
		s1.eng = 85;
		s1.math = 67;
		s1.sum = s1.kor+s1.eng+s1.math;
		s1.avg = s1.sum/3.0;
		s1.rank = 2;
		
		Score s2 = new Score();
		s2.name = "성춘향";
		s2.kor = 100;
		s2.eng = 95;
		s2.math = 98;
		s2.sum = s2.kor + s2.eng + s2.math;
		s2.avg = s2.sum/3.0;
		s2.rank = 1;
		
		System.out.println(s1);
		System.out.println(s2);
	}
}

 

결과 화면3

 

 

package kr.or.ddit.study06.sec02;

public class Point {
	/*
	 * x, y 좌표 만들기
	 */
	
	double x;
	double y;
	
	@Override
	public String toString() {
		return "점 [x=" + x + ", y=" + y + "]";
	}
}

 

package kr.or.ddit.study06.sec02;

public class PointExample {
	public static void main(String[] args) {
		/*
		 * 좌표 2개 각각 만들기.
		 */
		
		Point p1 = new Point();
		p1.x = 10.3;
		p1.y = 7.5;
		
		Point p2 = new Point();
		p2.x = 7.7;
		p2.y = 12.7;
		
		System.out.println(p1);
		System.out.println(p2);
	}
}

 

 

결과 화면4

 

 

package kr.or.ddit.homework;

public class HomeWork9 {
	public static void main(String[] args) {
		Score s1 = new Score();
		s1.name = "김영훈";
		s1.kor  = 85;
		s1.eng  = 72;
		s1.math = 81;
		s1.rank = 1;
		
		Score s2 = new Score();
		s2.name = "박채연";
		s2.kor  = 67;
		s2.eng  = 90;
		s2.math = 87;
		s2.rank = 1;
		
		Score s3 = new Score();
		s3.name = "최진호";
		s3.kor  = 77;
		s3.eng  = 79;
		s3.math = 94;
		s3.rank = 1;
		
		Score s4 = new Score();
		s4.name = "김미선";
		s4.kor  = 80;
		s4.eng  = 90;
		s4.math = 52;
		s4.rank = 1;
		
		Score s5 = new Score();
		s5.name = "서혜진";
		s5.kor  = 97;
		s5.eng  = 65;
		s5.math = 77;
		s5.rank = 1;
		
//		System.out.println(s1);
//		System.out.println(s2);
//		System.out.println(s3);
//		System.out.println(s4);
//		System.out.println(s5);
		
		// class에  class 배열이 담김
		Score[] scores = { s1, s2, s3, s4, s5 };
		
		// 총점과 평균 저장
		for (int i = 0; i < scores.length; i++) {
			Score sc1 = scores[i];
			sc1.sum = sc1.kor + sc1.eng + sc1.math;
			sc1.avg = sc1.sum/3.0;
		}
		
		// 출력
		System.out.println("총점과 평균 넣은 후");
		for (int i = 0; i < scores.length; i++) {
//			System.out.println(scores[i]);
			
			Score sc1 = scores[i];
			System.out.println(sc1);
		}
		System.out.println();
		
		// 랭크
		// i 내점수
		for (int i = 0; i < scores.length; i++) {
			Score sc1 = scores[i];
			// j 다른 사람 점수.
			for (int j = 0; j < scores.length; j++) {
				Score sc2 = scores[j];
				
				// 내 점수가 더 작다면 등수를 하나 증가
				if(sc1.sum < sc2.sum) {
					sc1.rank++;
				}
			}
		}
		
		// 정렬
		for (int i = 0; i < scores.length-1; i++) {
			for (int j = 0; j < scores.length-1; j++) {
				Score sc1 = scores[j];
				Score sc2 = scores[j+1];
				if(sc1.rank > sc2.rank) {
					Score temp = scores[j+1];
					scores[j+1] = scores[j];
					scores[j] = temp;
//					System.out.println(sc1);
				}
			}
		}
		
		// 정렬 후 출력
		System.out.println("정렬 후");
		for (int i = 0; i < scores.length; i++) {
			Score sc1 = scores[i];
			System.out.println(sc1);
		}
	}
}

class Score {
	/*
	 * 학생이름	name
	 * 	    국어
	 * 	    영어
	 * 	    수학
	 * 	    총점
	 * 	    평균
	 * 	    등수
	 */
	
	static String group = "404호";
	String name;
	int kor;
	int eng;
	int math;
	int sum;
	double avg;
	int rank;
	
	@Override
	public String toString() {
		return "Score [name=" + name + ", kor=" + kor + ", eng=" + eng + ", math=" + math + ", sum=" + sum + ", avg="
				+ avg + ", rank=" + rank + "]";
	}
	
}

 

결과 화면5

 

 

 

필드 선언

 

필드란 객체의 고유 데이터로 객체의 현재 상태 데이터 등을 저장한다. 데이터를 저장하는 공간을 만든다고 봐도 된다.

필드는 클래스 내부의 생성자메소드에서 바로 사용 가능하다. 하지만 클래스 외부에서 사용할 경우 객체를 생성하고 참조 변수를 통해서 사용해야 한다.

 

필드, 객체, 생성자, 메소드 예시

 

 

package kr.or.ddit.study06.sec02;

import java.util.Arrays;

public class ClassTypeExample {
	// 필드
	byte    b1;
	// ' ' <- \u0000
	char    c1;
	short   s1;
	int     i1;
	long    l1;
	
	float   f1;
	double  d1;
	
	boolean bl;
	
	// 기본으로 null이 들어감.
	int[] arr1;
	String sr1;
	
	public static void main(String[] args) {
		ClassTypeExample cte = new ClassTypeExample();
		// 클래스에 값을 넣지 않았을 때는 기본값이 들어감.
		System.out.println(cte);
	}
	
	@Override
	public String toString() {
		return "ClassTypeExample [b1=" + b1 + ", c1=" + c1 + ", s1=" + s1 + ", i1=" + i1 + ", l1=" + l1 + ", \nf1=" + f1
				+ ", d1=" + d1 + ", bl=" + bl + ", arr1=" + Arrays.toString(arr1) + ", sr1=" + sr1 + "]";
	}
}

 

결과 화면6

 

 

 

생성자 예시

 

생성자를 따로 만들지 않을 시에는 기본 생성자가 자동으로 생성되지만, 생성자를 생성 시에는 기본 생성자가 자동으로 생성되지 않는다.

기본 생성자를 이용하고 싶다면 따로 생성해야 한다.

 

package kr.or.ddit.study06.sec03;

public class ConstructExample {
	
	public static void main(String[] args) {
		ConstructExample ce1 = new ConstructExample();
		ConstructExample ce2 = new ConstructExample("테스트11");
	}
			
	// 기본 생성자 : 클래스 명과 동일
	// 파라미터가 있는게 없을 시 기본적으로 생성된다.
	public ConstructExample() {
		System.out.println("기본 생성자 입니다.");
	}
	
	// 기본 생성자x
	// 파라미터에 값이 있는게 있을 시 기본생성자를 사용하고 싶다면 기본 생성자를 따로 생성해야 한다.
	public ConstructExample(String test) {
		System.out.println("외부에서 주입된 데이터 : " + test);
		System.out.println("일반 생성자 입니다.");
	}
	
}

 

결과 화면7

 

 

package kr.or.ddit.study06.sec03;

public class Point {
	
	int x;
	int y;
	// 생성자 생성 방법
	// 클래스 명() {}
	Point() {
		
	}
	
	Point(int x1, int y) {
		// this는 class의 x와 y를 의미함.
		x = x1;
//		this.x = x;
		this.y = y;
	}

	@Override
	public String toString() {
		return "Point [x=" + x + ", y=" + y + "]";
	}
	
}

 

package kr.or.ddit.study06.sec03;

public class PointExample {
	public static void main(String[] args) {
		Point p1 = new Point();
		p1.x = 10;
		p1.y = 10;
		System.out.println(p1);
		
		// 객체를 생성하자마자 데이터를 넣음.
		Point p2 = new Point(10, 10);
		System.out.println(p2);
	}
}

 

결과 화면8

 

 

package kr.or.ddit.study06.sec03;

public class Member {
	/*
	 * 회원 가입
	 * id, pass, name, email
	 */
	String id;
	String pass;
	String name;
	String email;
	
	Member(String id, String pass, String name, String email) {
		this.id = id;
		this.pass = pass;
		this.name = name;
		this.email = email;
	}

	@Override
	public String toString() {
		return "Member [id=" + id + ", pass=" + pass + ", name=" + name + ", email=" + email + "]";
	}
}

 

package kr.or.ddit.study06.sec03;

public class MemberExample {
	public static void main(String[] args) {
		/*
		 * 회원 데이터 2개 입력해보기.
		 */
		
		Member m1 = new Member("test1", "1234", "이평강", "email");
		System.out.println(m1);
		
		Member m2 = new Member("test2", "pass2", "name2", "email2");
		System.out.println(m2);
	}
}

 

결과 화면9

 

 

package kr.or.ddit.study06.sec03;

public class Student {
	/*
	 * nation
	 * group
	 * name
	 * age
	 */
	
	String nation;
	String group;
	String name;
	int age;

	
	// alt + shift + s >> Generate Constructor using Fields.
	// 파라미터의 값에 따라 호출되는 위치가 달라지는 것을 오버로딩이라고 함.
	public Student(String name, int age) {
//		this.nation = "한국";
//		this.group = "404호";
//		this.name = name;
//		this.age = age;
		
		// Student(String group, String name, int age)의 클래스에 값이 그대로 들어감.
		// 아래와 같은 형식으로 할 시 모든 클래스를 수정하지 않아도 된다.
		this("404호", name, age);
	}

	public Student(String group, String name, int age) {
//		this.nation = "한국";
//		this.group = group;
//		this.name = name;
//		this.age = age;
		this("대한민국", group, name, age);
	}
	
	Student(String nation, String group, String name, int age) {
		this.nation = nation;
		this.group = group;
		this.name = name;
		this.age = age;
	}

	@Override
	public String toString() {
		return "Student [nation=" + nation + ", group=" + group + ", name=" + name + ", age=" + age + "]";
	}
	
}

 

package kr.or.ddit.study06.sec03;

public class StudentExample {
	public static void main(String[] args) {
		/*
		 * 일본, 404호, 이름, 나이
		 * 한국, 404호, 이름, 나이 *2
		 * 한국, 405호, 이름, 나이
		 */
		Student s1 = new Student("일본", "404호", "이름", 20);
		Student s2 = new Student("이름2", 21);
		Student s3 = new Student("이름3", 23);
		Student s4 = new Student("405호", "이름4", 24);
		
		System.out.println(s1);
		System.out.println(s2);
		System.out.println(s3);
		System.out.println(s4);
	}
}

 

결과 화면10-1

 

 

package kr.or.ddit.study06.sec03;

public class Student {
	/*
	 * nation
	 * group
	 * name
	 * age
	 */
	
	String nation;
	String group;
	String name;
	int age;

	
	// alt + shift + s >> Generate Constructor using Fields.
	// 파라미터의 값에 따라 호출되는 위치가 달라지는 것을 오버로딩이라고 함.
	public Student(String name, int age) {
//		this.nation = "한국";
//		this.group = "404호";
//		this.name = name;
//		this.age = age;
		
		// Student(String group, String name, int age)의 클래스에 값이 그대로 들어감.
		// 아래와 같은 형식으로 할 시 모든 클래스를 수정하지 않아도 된다.
		this("404호", name, age);
		System.out.println("파라미터 2개 생성자");
	}

	public Student(String group, String name, int age) {
//		this.nation = "한국";
//		this.group = group;
//		this.name = name;
//		this.age = age;
		this("대한민국", group, name, age);
		System.out.println("파라미터 3개 생성자");
	}
	
	Student(String nation, String group, String name, int age) {
		this.nation = nation;
		this.group = group;
		this.name = name;
		this.age = age;
		System.out.println("파라미터 4개 생성자");
	}

	@Override
	public String toString() {
		return "Student [nation=" + nation + ", group=" + group + ", name=" + name + ", age=" + age + "]";
	}
	
}

 

package kr.or.ddit.study06.sec03;

public class StudentExample {
	public static void main(String[] args) {
		/*
		 * 일본, 404호, 이름, 나이
		 * 한국, 404호, 이름, 나이 *2
		 * 한국, 405호, 이름, 나이
		 */
//		Student s1 = new Student("일본", "404호", "이름", 20);
//		Student s2 = new Student("이름2", 21);
//		Student s3 = new Student("이름3", 23);
//		Student s4 = new Student("405호", "이름4", 24);
//		
//		System.out.println(s1);
//		System.out.println(s2);
//		System.out.println(s3);
//		System.out.println(s4);
		
		Student s2 = new Student("이름2", 21);
	}
}

 

결과 화면10-2

 

 

package kr.or.ddit.study06.sec03;

public class Student {
	/*
	 * nation
	 * group
	 * name
	 * age
	 */
	
	String nation;
	String group;
	String name;
	int age;

	
	// alt + shift + s >> Generate Constructor using Fields.
	// 파라미터의 값에 따라 호출되는 위치가 달라지는 것을 오버로딩이라고 함.
	public Student(String name, int age) {
		this.nation = "한국";
		this.group = "404호";
		this.name = name;
		this.age = age;
		
		// Student(String group, String name, int age)의 클래스에 값이 그대로 들어감.
		// 아래와 같은 형식으로 할 시 모든 클래스를 수정하지 않아도 된다.
//		this("404호", name, age);
		System.out.println("파라미터 2개 생성자");
	}

	public Student(String group, String name, int age) {
		this.nation = "한국";
		this.group = group;
		this.name = name;
		this.age = age;
//		this("대한민국", group, name, age);
		System.out.println("파라미터 3개 생성자");
	}
	
	Student(String nation, String group, String name, int age) {
		this.nation = nation;
		this.group = group;
		this.name = name;
		this.age = age;
		System.out.println("파라미터 4개 생성자");
	}

	@Override
	public String toString() {
		return "Student [nation=" + nation + ", group=" + group + ", name=" + name + ", age=" + age + "]";
	}
	
}

 

package kr.or.ddit.study06.sec03;

public class StudentExample {
	public static void main(String[] args) {
		/*
		 * 일본, 404호, 이름, 나이
		 * 한국, 404호, 이름, 나이 *2
		 * 한국, 405호, 이름, 나이
		 */
//		Student s1 = new Student("일본", "404호", "이름", 20);
//		Student s2 = new Student("이름2", 21);
//		Student s3 = new Student("이름3", 23);
//		Student s4 = new Student("405호", "이름4", 24);
//		
//		System.out.println(s1);
//		System.out.println(s2);
//		System.out.println(s3);
//		System.out.println(s4);
		
		Student s2 = new Student("이름2", 21);
	}
}

 

결과 화면10-3

 

 

 

응용

 

package kr.or.ddit.study06.sec03;

public class Triangle {
	int x1;
	int y1;
	int x2;
	int y2;
	int x3;
	int y3;
	double area;
	
	public Triangle(int x1, int y1, int x2, int y2, int x3, int y3) {
		this.x1 = x1;
		this.y1 = y1;
		this.x2 = x2;
		this.y2 = y2;
		this.x3 = x3;
		this.y3 = y3;
		this.area = Math.abs
				( (x1*y2+x2*y3+x3*y1) - (x1*y3+x2*y1+x3*y2) )/2; // 삼각형 넓이 구하는 공식
	}
	
	// 데이터를 클래스로도 받을 수 있음.
	// Triangle(int x1, int y1, int x2, int y2, int x3, int y3)을 재활용해서 사용함.
	public Triangle(Point p1, Point p2, Point p3) {
		this(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
	}
	
}

 

package kr.or.ddit.study06.sec03;

public class TriangleExample {
	public static void main(String[] args) {
		Triangle t1 = new Triangle(0, 0, 10, 0, 0, 10);
		System.out.println("넓이는 " + t1.area);
		
		// Point 클래스
		// Point를 받을 수 있는 생성자가 필요함
		Triangle t2 = new Triangle(new Point(0,0), 
					   new Point(10,0), 
					   new Point(0,10));
		System.out.println("넓이는 " + t2.area);
	}
}

 

결과 화면11

 

 

 

메소드 예시

 

package kr.or.ddit.study06.sec04;

public class MethodExample01 {
	public static void main(String[] args) {
		MethodExample01 me = new MethodExample01();
		me.method1("파라미터1");
		me.method1("파라미터2");
		int sum = me.add(10, 9); // return 받은 19임
		System.out.println("메소드 add 에서 받은 값 : " + sum);
		int minus = me.minus(10, 9);
		System.out.println("메소드 minus 에서 받은 값 : " + minus);
	}
	
	// 메소드
	// 반복해서 계속 실행할 수 있음
	public void method1(String str) { // 괄호 안에 있는 것을 파라미터
		System.out.println("외부에서 입력된 파라미터 : " + str);
	}
	
	public int add(int a, int b) { // return 타입과 같이 int로 작성함.
		int sum = a+b;
		System.out.println(a + " + " + b + " = " + (a+b));
		return sum; // return 타입은 int
	}
	
	public int minus(int a, int b) {
		int minus = a-b;
		System.out.println(a + " - " + b + " = " + (a-b));
		return minus;
	}
}

 

결과 화면12

 

 

package kr.or.ddit.study06.sec04;

public class Member {
	String name;

	// 생성자
	public Member(String name) {
		this.name = name;
	}
}

 

package kr.or.ddit.study06.sec04;

import java.util.Scanner;

public class MemberAdd {
	Scanner sc = new Scanner(System.in);

	public static void main(String[] args) {
		MemberAdd obj = new MemberAdd();
		Member mem = obj.addMember("김수연");
		System.out.println(mem.name + "");
	}

	// 클래스인 Member을 돌려 보내기 위해 함.
	public Member addMember(String name) {
		Member mem = new Member(name);
		return mem;
	}	
}

 

결과 화면13

 

 

package kr.or.ddit.study06.sec04;

import java.util.Scanner;

public class MethodExample02 {
	Scanner sc = new Scanner(System.in);

	public static void main(String[] args) {
		MethodExample02 obj = new MethodExample02();
		System.out.println(obj.add(10, 10));
		System.out.println(obj.minus(10,10));
		System.out.println(obj.divide(10,10));
		System.out.println(obj.mult(10, 10));
	}
	
	/*
	 * 더하기, 빼기, 나누기, 곱하기 메소드 각각 만들고
	 * 값을 리턴 받아보자.
	 */
	
	public int add(int a, int b) {
		return a+b;
	}
	
	public int minus(int a, int b) {
		return a-b;
	}
	
	public double divide(int a, int b) {
		return (double)a/b;
	}
	
	public double mult(int a, int b) {
		return a*b;
	}
}

 

결과 화면14

 

 

package kr.or.ddit.study06.sec04;

import java.util.Scanner;

public class MethodExample03 {
	Scanner sc = new Scanner(System.in);

	public static void main(String[] args) {
		MethodExample03 obj = new MethodExample03();
		String name = obj.sc.nextLine();
		if(obj.chkKim(name)) {
			System.out.println(name + "는 김씨입니다.");
		} else {
			System.out.println(name + "는 김씨가 아닙니다.");
		}
	}
	
	/*
	 * 파라미터로 이름을 입력 받고
	 * 해당 성씨가 김씨인지 체크해보자.
	 * 아니라면 false 맞다면 true
	 */
	public boolean chkKim(String name) {
		if(name.startsWith("김")) return true;
		else return false;
	}
}

 

결과 화면15

 

 

+ static 설명 추가

package kr.or.ddit.study06.sec04;

public class MethodExample04 {
	// 객체가 만들어졌을 때 생성.
	int a = 10;
	static int b = 11;
	
	// static : 단 하나 밖에 없음.
	public static void main(String[] args) {
		MethodExample04 me = new MethodExample04();
		me.method1();
		method2();
	}
	
	// 객체가 만들어져야지 생성됨.
	public void method1() {
		System.out.println(a);
	}
	
	public static void method2() {
//		System.out.println(a); // static이 안 붙은 값을 가져올 수 없음
		System.out.println(b);
	}
}

 

결과 화면16

 

 

package kr.or.ddit.study06.sec04;

public class MethodExample04 {
	
	// static에서 불러오게 하기 위해선 객체 me를 생성해야 한다.
	// static 끼리는 객체를 생성하지 않아도 바로 부를 수 있다.
	public static void main(String[] args) {
		MethodExample04 me = new MethodExample04();
		me.method2();
	}
	
	public void method1() {
		System.out.println("메소드 1입니다.");
	}
	
	public void method2() {
		System.out.println("메소드 2입니다.");
		method1();
	}
}

 

결과 화면17

 

 

package kr.or.ddit.study06.sec04;

public class Car {
	int gas;
	
	public static void main(String[] args) {
		Car car = new Car(30);
		car.isLeftGas();
	}
	
	public Car(int gas) {
		this.gas = gas;
	}
	
	public boolean isLeftGas() {
		/*
		 * 가스가 없다면 == 0 return false;
		 * 가스가 있다면 연료가 gas 만큼 남았습니다.
		 * return true
		 */
//		int gas = 0; // 이 경우 아래에 있는 생략된 this를 추가해주어야 함.
		
//		Car car = new Car(10);
//		System.out.println("새로 생성된 car 객체에 가스 : " + car.gas);
//		System.out.println("원래 객체의 가스 : " + gas); // this를 생략함. 원래는 this.gas
		
		if(gas == 0) {
			System.out.println("연료가 없습니다.");
			return false;
		} else {
			System.out.println("연료가 " + gas + " 만큼 남았습니다.");
			return true;
		}
	}
	
	public void run() {
		/*
		 * 가스가 있을경우 "정상 운행이 가능합니다." 출력
		 * 		없을 경우 "연료가 부족합니다.. 바로 주유해야 합니다." 출력.
		 */
		gas--;
		if(isLeftGas()) {
			System.out.println("정상 운행이 가능합니다.");
		} else {
			System.out.println("연료가 부족합니다.. 바로 주유해야 합니다.");
		}
	}
}

 

package kr.or.ddit.study06.sec04;

public class CarExample {
	public static void main(String[] args) {
		Car car = new Car(10);
		while(car.isLeftGas()) {
			car.run();
		}
	}
}

 

결과 화면18

 

 

package kr.or.ddit.study06.sec04;

import java.util.Scanner;

public class Circle {
	Scanner sc = new Scanner(System.in);
	double PI = 3.141592;
	
	public static void main(String[] args) {
		Circle c = new Circle();
		System.out.println(c.getArea(10));
		System.out.println(c.getC(10));
	}
	
	/*
	 * 원의 넓이 구하는 메소드 만들기.
	 * PI * 반지름 * 반지름
	 * 리턴 타입 double;
	 */
	// 오버로딩 : 이름은 동일한데 파라미터만 다름
//	public double geArea(int r) {
//		return PI*r*r;
//	}
//	
	public double getArea(double r) {
		return PI*r*r;
	}
	
	// 같은 식을 두 번 쓰기엔 비효율적임
	public double geArea(int r) {
		return getArea((double)r);
	}
	
	/*
	 * 원주율 구하는 메소드 만들기.
	 * 파라미터 int, double 2가지 경우
	 * PI * 반지름 * 2
	 * 리턴 타입 double ;
	 */
	public double getC(int r) {
		return getC((double)r); 
	}
	
	public double getC(double r) {
		return PI*r*2; 
	}
	
}

 

결과 화면19

 

 

package kr.or.ddit.study06.sec04;

import java.util.Arrays;
import java.util.Random;

public class Lotto {
	int length = 6;
	
	public static void main(String[] args) {
		Lotto lotto = new Lotto();
//		lotto.generateLotto();
//		lotto.generatePaper();
		int[][][] bundle = lotto.generateBundle(17000);
		lotto.printBundle(bundle);
	}
	
	public void printBundle(int[][][] bundle) {
		for(int i=0; i<bundle.length; i++) {
			System.out.println("----------------------------");
			int[][] paper = bundle[i];
			for(int j=0; j<paper.length; j++) {
				int[] lotto = paper[j];
				System.out.println(Arrays.toString(lotto));
			}
			System.out.println("----------------------------");
		}
	}
	
	// 금액을 받아 로또 장 수만큼 만듬
	public int[][][] generateBundle(int money) {
		int p = money/1000/5;
		if(money/1000%5 != 0) p++;
		int[][][] bundle = new int[p][5][length];
		for(int i=0; i<bundle.length; i++) {
			bundle[i] = generatePaper();
		}
		// 오버로딩
		if(money/1000%5 != 0) {
			bundle[bundle.length-1] = 
					generatePaper(money/1000%5);
		}
		return bundle;
		
	}
	
	// lotto 1장 만들기 | num이 있을 시 달라짐
	public int[][] generatePaper(int num) {
		int[][] paper = new int[num][length];
		for(int i=0; i<paper.length; i++) {
			paper[i] = generateLotto();
		}
		return paper;
	}
	
	// lotto 1장 만들기
	public int[][] generatePaper() {
		/*
		 * lotto 5줄 만들기
		 */
		return generatePaper(5);
	}
	
	public int[] generateLotto() {
		/*
		 * 번호 6자리 로또 만들기.
		 */
		int[] lotto = new int[length];
		for(int i=0; i<length; i++) {
			int ran = new Random().nextInt(45)+1;
			lotto[i] = ran;
			for(int j=0; j<i; j++) {
				if(lotto[i] == lotto[j]) {
//					System.out.println(lotto[j] + " : 중복됨");
					i--;
					break;
				}
			}
		}
//		System.out.println(Arrays.toString(lotto));
//		System.out.println(array2String(lotto));
		
//		lotto = sortLotto(lotto);
		Arrays.sort(lotto);
		
//		System.out.println(array2String(lotto));
		return lotto;
	}
	
	// 캡슐화
	// lotto 작은 수에서 큰 수로 정렬
	public int[] sortLotto(int[] lotto) {
		for(int i=0; i<length-1; i++) {
			for(int j=0; j<length-1; j++) {
				if(lotto[j] > lotto[j+1]) {
					int temp = lotto[j];
					lotto[j] = lotto[j+1];
					lotto[j+1] = temp;
				}
			}
		}
		return lotto;
	}

	// Arrays.toString과 같은 기능
	public String array2String(int[] lotto) {
		String str = "[";
		for(int i=0; i<length; i++) {
			str += lotto[i];
			if(i != length-1) {
				str += ", ";
			}
		}
		str += "]";
		
		return str;
	}
}

 

결과 화면20

 

 

반응형

'자바' 카테고리의 다른 글

[Java 초급] 14장 String 메소드 종류  (2) 2023.12.19
[Java 초급] 13.5.1장 테스트1  (0) 2023.12.18
[Java 초급] 11.5장 테스트  (0) 2023.12.13
[Java 초급] 12장 배열 복사  (0) 2023.12.13
[Java 초급] 10.5.2장 테스트  (0) 2023.12.12