Back-end/Java 개념
Java - 클래스 정리 (4)
유로 청년
2022. 6. 27. 23:13
import java.util.Scanner;
public class GetSquareArea {
public static void sortRectangles(MyRectangle[] rect, int count) {
for(int end=count-1; end>0; end--) {
for(int start=0; start<end; start++) {
int beforeArea = rect[start].width * rect[start].heigth;
int afterArea = rect[start+1].width * rect[start+1].heigth;
if(beforeArea > afterArea) {
MyRectangle temp = rect[start];
rect[start] = rect[start+1];
rect[start+1] = temp;
}
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("사각형의 갯수 입력:");
int numberOfSquare = scan.nextInt();
MyRectangle[] rectangles = new MyRectangle[numberOfSquare];
System.out.println("사각형 정보(x, y, width, height) 입력:");
for(int i=0; i<numberOfSquare; i++) {
rectangles[i] = new MyRectangle();
rectangles[i].startPoint.x = scan.nextInt();
rectangles[i].startPoint.y = scan.nextInt();
rectangles[i].width = scan.nextInt();
rectangles[i].heigth = scan.nextInt();
}
sortRectangles(rectangles, numberOfSquare);
// 결과 출력
for(int i=0; i<numberOfSquare; i++) {
System.out.printf("%d 번째 사각형 -> Area : %d\n", i, rectangles[i].width* rectangles[i].heigth);
}
}
}
public class MyPoints {
int x;
int y;
}
public class MyRectangle {
public int width;
public int heigth;
public MyPoints startPoint;
}
목표) 사각형 정보{왼쪽-상단 (x,y 좌표), 폭, 높이} 입력 받아서 넓이가 작은 순서대로 나열하자.
이를 위해 다음과 같이 코드를 작성하였다.
- 왼쪽 상단 x,y 좌표를 객체를 통해 관리하기 위해 MyPoints 클래스 정의
- MyPoints 클래스와 폭, 높이를 담을 수 있는 MyRectangle 클래스 정의
- MyRectangle 타입의 배열인 rectangles를 정의하여 여러 개의 사각형 정보를 입력받는다.
- 이를 위해 new 명령어를 통해 numberOfSquare 개의 배열 생성하였으며, 배열의 각각의 원소에 데이터를 입력 받기 전에 new 명령어를 통해 MyRectangle 타입의 객체를 생성하였다.
(왜냐하면 배열의 각 원소는 primitive 타입이 아닌 MyRectangle 타입이기 때문에 rectangles[i]는 참조 변수이며, 참조 변수는 객체의 주소를 저장할 뿐, 실질적으로 데이터를 저장하지 않는다. 따라서 데이터를 저장하기 위해 new 명령어를 통해 이름 없는 객체를 만든 뒤, 이 객체에 데이터를 저장하고, 객체의 주소를 참조 변수에 저장시킨다.) - 그리고 BubbleSort를 통해 정렬한다.
하지만, 예상치 못한 에러가 발생하였다. 무엇이 문제인가?
→ 사각형 x,y 좌표를 넣는 과정에서 에러가 발생하였다.
rectangles[i].startPoint.x = scan.nextInt();
rectangles[i].startPoint.y = scan.nextInt();
그 이유는 startPoint는 primitive 타입이 아니라 사용자 정의 타입, 즉 rectangles 타입이기 때문이다. MyRectangle 클래스 내부를 보게 되면 startPoint 객체가 rectangles 타입임을 확인할 수 있다. 이는 startPoint 객체는 참조 변수이기 때문에 new 명령어로 생성된 객체의 주소를 저장할 뿐, 실질적인 데이터를 저장하지 못한다.
그런데, 위 코드를 보면 startPoint 참조 변수에 x값과 y값을 대입하려고 하고 있다. 바로 이 부분이 문제였던 것이다.
그럼 해결책은 무엇인가?
→ x, y 좌표값을 대입하기 전에 new 명령어로 객체를 생성한 뒤, x, y 좌표값을 대입하면 된다.
rectangles[i].startPoint = new MyPoints();
rectangles[i].startPoint.x = scan.nextInt();
rectangles[i].startPoint.y = scan.nextInt();
new 명령어를 통해 MyPoints 타입의 객체를 생성한 뒤, 생성된 객체에 x, y 좌표값을 대입하고, 객체의 주소(참조)값을 참조 변수에 저장하면 해결 가능하다.