본문 바로가기
study/Java

[Java] 19. 클래스 구현

by 금이패런츠 2022. 3. 18.
728x90
반응형
package chap6;
/*
 * Car2 클래스 구현
 *  멤버변수 : color, number, width, height, sno, cnt
 * 
 * 구동 클래스
 *  자동차 5개 생성
 *  자동차 색상    : 빨강, 노랑, 파랑, 초록, 검정 중 한개를 임의의 설정
 *  자동차 번호    : 임의의 4자리 수로 설정하기
 *  생산번호      : 순차적으로 번호 지정
 *  자동차 생산건수 : cnt로 지정 
 */
class Car2 {
	String color;
	int number;
	static int width = 200;
	static int height = 120;
	int sno;
	static int cnt;
	public String toString() {
		return color + ", " + number + "(" + width + "," + height + ")" + ", 자동차번호:" + sno + ", 전체자동차생산갯수:" + cnt;
	}
}
public class CarEx2 {
	public static void main(String[] args) {
    
		Car2[] arr = new Car2[5];
		String[] colors = {"빨강", "노랑", "파랑", "초록", "검정"};
		for (int i=0; i<arr.length; i++) { //0 => 4
			
			arr[i] = new Car2();
			
			int cidx = (int)(Math.random() * colors.length); // 0 ~ 4사이의 임의의 정수
			arr[i].color = colors[cidx];
			 
			//  9000 <= x < 10000.0
			int n = (int)(Math.random() * 9000) + 1000; // 임의의 4자리 정수
			arr[i].number = n;
			
			arr[i].sno = ++Car2.cnt; //5
			
			System.out.println(arr[i]);
		}
	}
}
728x90
반응형