클래스란?
클래스(class)는 서로 다른 여러 데이터형을 자유로이 조합하여 만들 수 있는 자료구조입니다.
클래스에서 배열 구현하기
// 신체검사 데이터용 클래스 배열에서 평균 키와 시력의 분포를 구함
import java.util.Scanner;
class PhysicalExamination {
static final int VMAX = 21; // 시력의 분포(0.0부터 0.1 단위로 21개)
static class PhyscData {
String name; // 이름
int height; // 키
double vision; // 시력
//--- 생성자(constructor) ---//
PhyscData(String name, int height, double vision) {
this.name = name;
this.height = height;
this.vision = vision;
}
}
//--- 키의 평균값을 구함 ---//
static double aveHeight(PhyscData[] dat) {
double sum = 0;
for (int i = 0; i < dat.length; i++)
sum += dat[i].height;
return sum / dat.length;
}
//--- 시력의 분포를 구함 ---//
static void distVision(PhyscData[] dat, int[] dist) {
int i = 0;
dist[i] = 0;
for (i = 0; i < dat.length; i++)
if (dat[i].vision >= 0.0 && dat[i].vision <= VMAX / 10.0)
dist[(int)(dat[i].vision * 10)]++;
}
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
PhyscData[] x = {
new PhyscData("강민하", 162, 0.3),
new PhyscData("김찬우", 173, 0.7),
new PhyscData("박준서", 175, 2.0),
new PhyscData("유서범", 171, 1.5),
new PhyscData("이수연", 168, 0.4),
new PhyscData("장경오", 174, 1.2),
new PhyscData("황지안", 169, 0.8),
};
int[] vdist = new int[VMAX]; // 시력의 분포
System.out.println("■ 신체검사 리스트 ■");
System.out.println(" 이름 키 시력");
System.out.println("--------------------");
for (int i = 0; i < x.length; i++)
System.out.printf("%-6s%3d%5.1f\n",
x[i].name, x[i].height, x[i].vision);
System.out.printf("\n평균 키: %5.1fcm\n", aveHeight(x));
distVision(x, vdist); // 시력의 분포를 구함
System.out.println("\n시력 분포");
for (int i = 0; i < VMAX; i++)
System.out.printf("%3.1f~: %2d명\n", i / 10.0, vdist[i]);
}
}
간단한 클래스의 예
public class A {
private int f1; // 비공
protected int f2; // 한정 공개 필드
public int f3; // 공개 필드
static final int S1 = 0; // 정적 상수 필드
public A() { // 생성자
f1 = f2 = f3 = 0;
}
public A(int f1, int f2, int f3) { // 생성자
this.f1 = f1;
this.f2 = f2;
this.f3 = f3;
}
public void setF1(int f) { // 메서드 f1의 setter
f1 = f;
}
public int getF1() { // 메서드 f1의 getter
return f1;
}
}
간단하게 클래스를 알아보았다.
클래스의 자세한 내용은 여기 에 적어 뒀으니 참고하자.
'Algorithm > 개념 정리' 카테고리의 다른 글
[알고리즘 문제 해결 전략] 1. 문제 해결 시작하기 (0) | 2022.12.04 |
---|---|
[알고리즘 문제 해결 전략] 시작하기 (0) | 2022.12.04 |
배열 복제하기 (0) | 2022.11.11 |
소수 나열하기 (0) | 2022.11.11 |
기수 변환하기 (0) | 2022.11.11 |