본문 바로가기

프로그래밍 공부/java

[JAVA] 도형 클래스를 객체를 생성하여 도형의 넓이를 구하는 프로그램 만들기

반응형
import java.util.Scanner;

class Triangle{
	double width=0;
	double height=0;
		
	double triangle_area() {
		return (width*height)/2;
	}
}

class Square{
	int width=0;
	int height=0;
	
	int square_area() {
		return(width*height);
	}
}

class Circle{
	double radius = 0;
	
	double circle_area() {
		return(radius*radius*3.14);
	}
}

public class Shape {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		Triangle triangle = new Triangle();
		Square square = new Square();
		Circle circle = new Circle();
		
		System.out.println("넓이를 구할 도형을 입력하세요.");
		System.out.println("1.삼각형  2.사각형  3.원");
		int choice = sc.nextInt();
		
		if(choice == 1) {
			System.out.print("밑변과 높이를 입력하세요 >> ");
			triangle.width = sc.nextInt();
			triangle.height = sc.nextInt();
			System.out.println("삼각형의 넓이는 " + triangle.triangle_area());
		}else if(choice == 2) {
			System.out.print("밑변과 높이를 입력하세요 >> ");
			square.width = sc.nextInt();
			square.height = sc.nextInt();
			System.out.println("사각형의 넓이는 " + square.square_area());
		}else if(choice == 3) {
			System.out.println("반지름의 길이를 입력하세요 >> ");
			circle.radius = sc.nextDouble();
			System.out.println("원의 넓이는 " + circle.circle_area());
		}else {
			System.out.println("잘못 입력하셨습니다.");
		}
	}
}
반응형