밑변과 높이 정보를 저장할 수 있는 Triangle 클래스 정의
main 클래스에 생성과 동시에 초기화가 가능한 생성자 정의
밑변과 높이 정보를 변경시킬 수 있는 메소드를 정의하여 삼각형의 넓이를 계산해서 반환하는 메소드 객체를 구현
public class TriangleMain {
public static void main(String[] args) {
//생성과 동시에 초기화가 가능한 생성자도 정의
Triangle ta0 = new Triangle(3,5);
Triangle ta1 = new Triangle(4,2);
Triangle ta2 = new Triangle(6,10);//
ta0.res();
ta1.res();
ta2.res();
}
}
public class Triangle {
private int base;
private int height;
public Triangle(int base, int height) {
this.base = base;
this.height = height;//정보를 변경시킬수있는 메소드정의
}
void res() {
System.out.printf("삼각형의 넓이는 %d이다.\n", base * height / 2);//넓이를 계산해서 반환
}
}
'java > java exercise' 카테고리의 다른 글
별찍기 (0) | 2020.01.28 |
---|---|
Print multiplication tables in vertical direction (0) | 2020.01.27 |
Identify x and y are in the rectangle zone (0) | 2020.01.25 |
It will add everything until you're satisfied. (0) | 2020.01.25 |
Generate multiplication table of a given number (0) | 2020.01.25 |