2장 실습문제 8번.
8. 2차원 평면에서 직사각형은 왼쪽 상단 모서리와 오른쪽 하단 모서리의 두 점으로 표현된다. 키보드로부터 사각형을 구성하는 두 점(x1, y1), (x2, y2)를 입력받아 100,100과 200,200의 두 점으로 이루어진 사각형과 충돌하는지 판별하는 프로그램을 작성하라. (아래 코드를 참고하여 만드시오)
다음은 점(x,y)가 사각형 (rectx1, recty1), (rectx2, recty2)
안에 있으면 true를 리턴하는 메소드이다.
이를 활용하라.
public static boolean inRect(int x, int y, int rectx1, int rectx2, int recty1, int recty2){
if ((x>=rectx1 && x<=rectx2) && (y>=recty1 && y<=recty2))
{ return true; }
else { return false; }
A:
package ch2;
import java.util.Scanner;
public class Ch2 {
//실습문제 8
public static boolean inRect(int x, int y,
int rectx1, int rectx2, int recty1, int recty2) {
if((x>=rectx1 && x<=rectx2) && (y>=recty1 && y<=recty2))
return true;
else
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("두 점 (x1, y1), (x2, y2)의 좌표를 입력하시오 >>");
Scanner s = new Scanner(System.in);
int x1 = s.nextInt();
int y1 = s.nextInt();
int x2 = s.nextInt();
int y2 = s.nextInt();
if (inRect(x1, y1, 100, 100, 200, 200) ||
inRect(x2, y2, 100, 100, 200, 200) ||
inRect(x1, y2, 100, 100, 200, 200) ||
inRect(x2, y1, 100, 100, 200, 200))
System.out.println("사각형이 겹칩니다.");
else if (inRect(x1, y1, 100, 100, 200, 200) &&
inRect(x2, y2, 100, 100, 200, 200) &&
inRect(x1, y2, 100, 100, 200, 200) &&
inRect(x2, y1, 100, 100, 200, 200))
System.out.println("사각형이 겹칩니다.");
else if ((inRect(100,100,x1,y1,x2,y2)) &&
inRect(100,200,x1,y1,x2,y2) &&
inRect(200,100,x1,y1,x2,y2) &&
inRect(200,200,x1,y1,x2,y2))
System.out.println("사각형이 겹칩니다.");
else
System.out.println("사각형이 겹치지 않습니다.");
s.close();
}
}