문제 풀이) 배열 객체, 클래스, getter, 스캐너

2021. 12. 12. 21:38카테고리 없음

사각형을 표현하는 다음 Rect 클래스를 활용하여 Rect 객체 배열을 생성하고, 사용자로부터 4개의 사각형을 입력받아 배열에 저장한 뒤, 배열을 검사하여 사각형 면적의 합을 출력하는 main()메소드를 가진 RectArray 클래스를 작성하라. 

 

 


 

 

 

1.클래스 생성

class Rect {
	private int width, height;
	public Rect(int width, int height) {
		this.width=width;
		this.height=height;
	}
	public int getArea() {return width*height;}
}

 

 

2. 객체 배열 생성

Rect [] rect=new Rect [4];

 

3. 스캐너 후, 새로운 객체에 저장

int width=scanner.nextInt();
int height=scanner.nextInt();
			
rect[i]= new Rect(width, height);

 

 

4, Rect 클래스에 있는  getArea 메소드  호출

sum=sum+rect[i].getArea();

 

달려간댜

 

5. 최종

import java.util.Scanner;

class Rect {
	private int width, height;
	public Rect(int width, int height) {
		this.width=width;
		this.height=height;
	}
	public int getArea() {return width*height;}
}


public class Main {

	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		
		Rect [] rect=new Rect [4];
		
		for(int i=0; i<rect.length; i++) {
			System.out.println(i+1);
			System.out.println("너비와 높이 > > ");
			int width=scanner.nextInt();
			int height=scanner.nextInt();
			
			rect[i]= new Rect(width, height);
		
		}
			System.out.println("저장했습니다. ");
			int sum=0;
			
		for(int i=0; i>rect.length; i++);
			sum=sum+rect[i].getArea();
			
			System.out.println("사각형 전체 합은"+sum);
			scanner.close();
	}

}