04.25 클래스, 객체배열
package e_reference;
class Engine{
int maxSpeed;
int rpm;
}
public class Car {
String company;
String model;
int speed;
Engine engine;
}
package e_reference;
// main method가 포함된 class
// 실행 class
public class CarExample {
public static void main(String[] args) {
Car car = new Car();
System.out.println(car);
car.company = "현대자동차";
car.model = "싼타페";
car.speed = 0;
Engine engine = new Engine();
engine.maxSpeed = 300;
engine.rpm = 0;
//car.engine에 engine의 주소값 대입
car.engine = engine;
//car.engine의 주소값 = engine의 주소값
System.out.println(car.engine == engine);
System.out.println(car.engine);
System.out.println(engine);
car.engine.maxSpeed = 280;
car.engine.rpm = 2000;
System.out.println(engine.maxSpeed);
System.out.println(engine.rpm);
Car car2 = new Car();
car2.company = "KIN";
car2.model = "morning";
car2.engine = new Engine();
car2.engine = engine;
car2.engine.maxSpeed = 200;
car2.engine.rpm = 100;
}
}
package f_cooperation;
public class Bus {
int busNumber; // 버스 번호
int passengerCount; // 승객 수
int money; // 버스의 수입
//버스 번호를 매개변수로 넘겨받는 생성자 - 버스번호 초기화
Bus(int busNumber){
this.busNumber = busNumber;
}
// 승객 탑승 시 금액 지불
void take(int money) {
this.money += money;
this.passengerCount++;
}
// 버스의 정보를 출력하는 method
void showInfo() {
System.out.printf("버스 %d번의 승객은 %d명이고, 현재 수입은 %,d원입니다.%n",
busNumber,
passengerCount,
money);
}
}
package f_cooperation;
public class Subway {
String lineNumber; //지하철 노선 번호
int passengerCount; //승객수
int money; //수입
// 객체 생성 시 지하철 노선 번호를 초기화 하는 생성자
// alt + s + a
Subway(String lineNumber) {
this.lineNumber = lineNumber;
}
// 승객 탑승 시 금액 지불
void take(int money) {
this.money += money;
this.passengerCount++;
}
void showInfo() {
System.out.printf(
"%s 지하철의 승객은 %d명이고, 현재 수입은 %,d입니다. %n",
lineNumber, passengerCount, money
);
}
}
package f_cooperation;
/**
* @since 20230420_5
* @apiNote 버스, 지하철 등의 탈것 객체와 사용자 객체간의 협력관계
*
*
*/
public class TakeVehicle {
public static void main(String[] args) {
//정의된 생성자가 존재하므로 컴파일러가 기본 생성자를 추가하지 않는다.
//Bus bus5 = new Bus();
Bus bus100 = new Bus(100);
bus100.showInfo();
Bus bus120 = new Bus(120);
bus120.showInfo();
Subway subwayGreen = new Subway("2호선");
subwayGreen.showInfo();
Student studentKim = new Student("김선국");
Student studentLee = new Student("이진형",2,1000000);
studentKim.showInfo();
studentLee.showInfo();
studentKim.takeBus(bus100);
studentLee.takeBus(bus120);
bus100.showInfo();
bus120.showInfo();
Worker workerChoi = new Worker("최기근",2100000000);
workerChoi.showInfo();
workerChoi.takeVehicle(bus120);
workerChoi.takeVehicle(subwayGreen);
workerChoi.showInfo();
bus120.showInfo();
subwayGreen.showInfo();
bus100.showInfo();
}
}
package f_cooperation;
public class Student {
String studentName; // 학생이름
int grade; // 학년 -1 : 초등, 2 : 중등, 3 : 고등
int money; // 학생이 보유한 금액
Student(String studentName){
this(studentName,3,10000); // this() : 내가 가지고 있는 생성자 호출
/*
this.studentName = studentName;
this.grade = 3;
this.money = 10000;
*/
}
Student(String studentName, int money){
this(studentName,3,money);
/*
this.studentName = studentName;
this.grade = 3;
this.money = money;
*/
}
// alt + s + a
Student(String studentName, int grade, int money) {
super();
this.studentName = studentName;
this.grade = grade;
this.money = money;
}
// 버스 탑승
void takeBus(Bus bus) {
int pay = 0;
switch(grade) {
case 1:
pay = 600;
break;
case 2:
pay = 800;
break;
case 3:
pay = 1000;
break;
}
bus.take(pay);
this.money -= pay;
}
void takeSubway(Subway subway) {
int pay = 0;
switch(grade) {
case 1:
pay = 700;
break;
case 2:
pay = 900;
break;
case 3:
pay = 1100;
break;
}
subway.take(pay);
this.money -= pay;
}
//학생이 보유한 금액 정보를 출력
void showInfo() {
System.out.printf(
"%s님의 남은 돈은 %,d원 입니다. %n",
studentName, money
);
}
}
package f_cooperation;
public class Worker {
String workerName; //직장인 이름
int money; //보유 금액
Worker(String workerName, int money) {
this.workerName = workerName;
this.money = money;
}
//타는건 똑같으니까 오버로딩해서 작성하면 더 나음~^^
//객체 타입도 구분이 가능하다.
void takeVehicle(Bus bus) {
bus.take(1200);
money -=1200;
}
void takeVehicle(Subway subway) {
subway.take(1300);
money -=1300;
}
void showInfo() {
System.out.println(workerName + "님의 남은 금액은 " + money + "입니다.");
}
}
객체배열
package g_object_array;
public class Korean {
String nation = "대한민국";
String name;
String birth;
int age;
}
package g_object_array;
public class KoreanExample {
public static void main(String[] args) {
Korean[] koreans = new Korean[3];
// koreans : 참조타입의 배열.
// [0] [1] [2]
// [null][null][null]
// 이차원배열이랑 개념이 비슷하다고 보면 된다.
System.out.println(koreans);
System.out.println(koreans[0]);
System.out.println(koreans[1]);
System.out.println(koreans[2]);
Korean k1 = new Korean();
koreans[0] = k1;
//[k1][null][null]
koreans[0].name = "이순신";
koreans[0].birth = "1678";
koreans[0].age = 356;
// koreans[1].name = "홍길동"; -> nullpointException오류
// 넘겨받은 값이 초기화가 되었는지 아닌지 모를때는 null값 확인을 위해서 null을 체크해줘야한다.
if(koreans[1]!=null) {
koreans[1].name="홍길동";
}
for(int i=0;i<koreans.length;i++) {
if(koreans[i] !=null) {
System.out.println(koreans[i].nation);
System.out.println(koreans[i].name);
System.out.println(koreans[i].birth);
}
}
}
}
package g_object_array;
// Value Object (VO) : 수행 기능이 없고 그냥 데이터만 저장하는 class
// 성적 관리용 학생 class
// 학생에 대한 정보를 저장하기 위해 설계된 class
public class Student {
int number; //학번
String name; //학생이름
int score; //점수
Student() {}
Student(int number, String name, int score) {
this.number = number;
this.name = name;
this.score = score;
}
String getInfo() {
return "number : " + number + ", name: " + name + ", score: " + score;
}
}
package g_object_array;
// 실행 클래스
public class StudentExample {
public static void main(String[] args) {
//변수 저장할 필요가 없이 생성자에서 모든게 끝나니까 생성자만 입력해줌. 생성자 호출만 함.
new StudentManagement();
}
}
package g_object_array;
import java.util.Scanner;
public class StudentManagement {
Scanner sc;
Student[] students; // 점수를 저장할 학생 배열
int stuCount; // 학생수
int selectNo; // 메뉴 선택 번호
StudentManagement(){
sc = new Scanner(System.in);
run();
}
void run() {
menu : while(true) {
System.out.println("=====================================");
System.out.println("1.학생수|2.정보입력|3.정보확인|4.분석|5.종료");
System.out.println("=====================================");
System.out.println("메뉴 번호를 입력해주세요.");
selectNo = sc.nextInt();
if(selectNo != 1 && selectNo != 5 && students == null) {
System.out.println("학생 수를 먼저 입력해주세요.");
continue;
}
switch(selectNo) {
case 1 :
createStudents();
break;
case 2:
insertInfo();
break;
case 3:
readInfo();
break;
case 4:
analysis();
break;
case 5:
System.out.println("프로그램 종료");
break menu;
default :
System.out.println("사용할 수 없는 번호입니다.");
}
}// end while
}// end run
//1. 학생수
void createStudents() {
System.out.println("학생 수 입력");
stuCount = sc.nextInt();
students = new Student[stuCount];
System.out.println("등록할 학생 수는 : "+students.length);
}
void insertInfo() {
System.out.println("학생 정보 입력");
for(int i=0; i< students.length; i++) {
int num = i+1;
System.out.println(num+"번 학생의 이름을 입력해주세요 > ");
String name = sc.next();
System.out.println(num+"번 학생의 점수를 입력해주세요 > ");
int score = sc.nextInt();
Student stu = new Student(num,name,score);
// stu.number = num;
// stu.name = name;
// stu.score = score;
students[i] = stu;
}
}
//3. 학생 정보 확인
void readInfo() {
System.out.println("학생 정보 확인");
if(students[students.length-1] == null) {
System.out.println("학생 정보를 입력해주세요.");
return; //null 인 경우 메소드 즉시 종료
}
for(Student s : students) {
System.out.println(s.getInfo());
}
}
//4. 분석
void analysis() {
System.out.println("학생 정보 분석");
if(students[0] !=null) {
int total = 0;
double avg = 0.0;
int max, min;
max = min = students[0].score;
Student stuMin, stuMax;
stuMin = stuMax = students[0];
for(int i = 0; i< students.length; i++) {
int score = students[i].score;
total += score;
// 최고점수, 최고득점자
if(max < score) {
max = score;
stuMax = students[i];
}
// 최저점수 , 최저득점자
if(min > score) {
min = score;
stuMin = students[i];
}
}//end for
System.out.println("전체점수 : "+ total);
avg = total / (double)stuCount;
System.out.printf("평균점수 : %.1f %n",avg);
System.out.println("최고점수 : "+max);
System.out.println("최저점수 : "+min);
System.out.println("최고득점자 : "+stuMax.getInfo());
System.out.println("최저득점자 : "+stuMin.getInfo());
}else {
System.out.println("학생정보를 먼저 입력해주세요.");
}
}
}