평면상에 좌표축에 평행한 n개의 직사각형에 과한 데이터를 입력 받은 후 면적이 작은 것부터 큰 것 순으로 정렬하여

출력하는 프로그램을 작성하라

 

입력 파일의 형식: 

0 1 2 4

1 4 7 8

4 3 12 9

8 18 11 30

5 10 6 11

 

맨 앞 두정수가 좌상단의 꼭지점 좌표!

세번째 정수는 너비

네번째는 높이이다.

 

package section1;

public class Mypoint1 {
	public int x;
	public int y;
}

좌표를 저장하는 클래스

package section1;

public class MyRectangle1 {
	public Mypoint1 lu;
	public int width;
	public int height;
}

사각형 정보를 저장할 클래스

 

 

 

package section1;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class code05 {

	static MyRectangle1[] rects = new MyRectangle1[100];
	static int n = 0;
	
	public static void main(String[] args) {
		
		try {
			Scanner in = new Scanner(new File("data.txt"));
			
			while(in.hasNext()) {
			rects[n] = new MyRectangle1();
			rects[n].lu= new Mypoint1();
			rects[n].lu.x = in.nextInt();
			rects[n].lu.y = in.nextInt();
			rects[n].width = in.nextInt();
			rects[n].height = in.nextInt();
			n++;
			}
			in.close();
		} catch (FileNotFoundException e) {
			System.out.println("no data file");
			System.exit(1);
		}
		bubbleSort();
	
		for(int i =0;i<n;i++) 
			System.out.println(rects[i].lu.x + " "+ rects[i].lu.y + " "+rects[i].width + " " + rects[i].height);
		}
		private static void bubbleSort() {
			for(int i = n-1;i>0;i--) {
				for(int j =0; j<i; j++) {
					if(calArea(rects[j]) > calArea(rects[j+1])) {
						MyRectangle1 tmp = rects[j];
						rects[j] = rects[j+1];
						rects[j+1] = tmp;
					}
				}
			}
		}
		public static int calArea(MyRectangle1 r) {
			return r.width * r.height;
		}
}


 항상 객체안에 내용을 건들때 자꾸 new로 생성을 해주고 건들어야한다는 것을 

까먹는다.. 객체 안에 객체가 들어있기때문에 

rects[n] = new MyRectangle1();
rects[n].lu= new Mypoint1();

이부분에서 약간 애를 먹었다.

'알고리즘 with 자바 > 자료구조' 카테고리의 다른 글

메서드와 생성자 1  (0) 2021.06.23
클래스 ,객체, 참조변수 5  (0) 2021.06.23
클래스, 객체, 참조변수 3  (0) 2021.06.22
클래스, 객체, 참조변수 2  (0) 2021.06.21
클래스 , 객체, 참조변수 1  (0) 2021.06.21

+ Recent posts