본문 바로가기
수업(국비지원)/Java

[Java] chap6 : 클래스와 객체 - 클래스 구현

by byeolsub 2023. 4. 15.

📌

package chap6;
/*
Car2 클래스 구현
멤버 변수 : color, number, width, height, sno, cnt

구동 클래스
자동차 5개 생성
자동차 색상 : 빨강, 노랑, 파랑, 초록, 검정 중 한개를 임의의 설정
자동차 번호 : 임의의 4자리수로 설정하기
생산 번호 : 순차적으로 번호 지정
자동차 생산 건수 : cnt로 지정
*/
class Car2 {
   String color;
   int number;
   static itn 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[] arg) {
      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]);
      }
   }
}