문자형 2차원 배열 5행 5열을 만들과 행과 열을 입력 받아 해당 좌표의 값을 'X'로 변환해 2차원 배열을 출력하시오. 또한 계속해서 반복 실행하도록 구현하고 행이나 열 입력 시 0미만 5이상의 수가 입력되면 프로그램을 종료하시오.
import java.util.Scanner;
class Matrix {
private int col, row;
public void setCol(int col) {
if (col < 0 || 5 <= col) {
System.exit(0);
}
this.col = col;
}
public void setRow(int row) {
if (row < 0 || 5 <= row) {
System.exit(0);
}
this.row = row;
}
public void play() {
Scanner scanner = new Scanner(System.in);
int[][] matrix = new int[5][5];
while (true) {
System.out.print("행 인덱스 입력 >> ");
setRow(scanner.nextInt());
System.out.print("열 인덱스 입력 >> ");
setCol(scanner.nextInt());
matrix[row][col] = 1;
System.out.println(" 0 1 2 3 4");
for (int i = 0; i < 5; i++) {
System.out.print(i + " ");
for (int j = 0; j < 5; j++) {
if (matrix[i][j] == 1) {
System.out.print("X ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
}
public class Hw1 {
public static void main(String[] args) {
Matrix matrix = new Matrix();
matrix.play();
}
}
다음 멤버를 가지고 직사각형을 표현하는 Rectangle 클래스를 작성하라.
- int 타입의 x, y, width, height 필드: 사각형을 구성하는 점과 크기 정보
- x, y, width, height 값을 매개변수로 받아 필드를 초기화하는 생성자
- int square() : 사각형 넓이 리턴
- void show() : 사각형의 좌표와 넓이를 화면에 출력
- boolean contatins(Rectangle r) : 매개변수로 받은 r이 현 사각형 안에 있으면 true 리턴
- main() 메소드의 코드와 실행 결과는 다음과 같다
public static void main(String[] args) {
Rectangle r = new Rectangle(2, 2, 8, 7);
Rectangle s = new Rectangle(5, 5, 6, 6);
Rectangle t = new Rectangle(1, 1, 10, 10);
r.show();
System.out.println("s의 면적은 "+s.square());
if(t.contains(r)) System.out.println("t는 r을 포함합니다.");
if(t.contains(s)) System.out.println("t는 s를 포함합니다.");
}
(2,2)에서 크기가 8x7인 사각형
s의 면적은 36
t는 r을 포함합니다.
class Rectangle{
private int x, y, width, height;
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public int square() {
return width * height;
}
public void show() {
//사각형의 좌표와 넓이를 화면에 출력
System.out.println("(" + x + ", " + y + ")" + "에서 크기가 " + width + "x" + height + "인 사각형");
}
public boolean contains(Rectangle r) {
boolean leftBottom = false;
boolean rightTop = false;
if (x < r.x && r.x < x + width && y < r.y && r.y < y + height) {
leftBottom = true;
}
if (x < r.x + r.width && r.x + r.width < x + width && y < r.y + r.height && r.y + r.height < y + height) {
rightTop = true;
}
return leftBottom && rightTop;
}
}
public class Hw2 {
public static void main(String[] args) {
Rectangle r = new Rectangle(2, 2, 8, 7);
Rectangle s = new Rectangle(5, 5, 6, 6);
Rectangle t = new Rectangle(1, 1, 10, 10);
r.show();
System.out.println("s의 면적은 "+s.square());
if(t.contains(r)) System.out.println("t는 r을 포함합니다.");
if(t.contains(s)) System.out.println("t는 s를 포함합니다.");
}
}