개발 일지/Day by day
2024-01-23 TIL
쁘띠뀨띠
2024. 1. 24. 00:04
다음 코드를 참고해서 생성한 자동차 수 출력하는 프로그램 완성하기
package static2.ex;
public class CarMain {
public static void main(String[] args) {
Car car1 = new Car("k3");
Car car2 = new Car("G80");
Car car3 = new Car("Model Y");
Car.showTatalCars();
//구매한 차량 수를 출력하는 static메서드
}
}
Car 클래스 생성 후 생성자를 먼저 만들었다.
k3, g80, modelY를 갖고 객체를 만들기 때문에 String model 받는 생성자로 만들고 필드도 같이 생성
Class변수인 static제어자를 붙여 int count선언후 객체를 생성할때마다 ++;
showTotalCars()메서드에는 count 출력
package static2.ex;
public class Car {
private static int count;
private String model;
public Car(String model) {
this.model = model;
count++;
}
public static void showTotalCars() {
System.out.println(count);
}
}
배열용 수학 유틸리티(MathArrayUtils) 만들기
sum(int[] array) : 배열의 모든 요소의 합
average(int[] array) : 배열의 모든 요소 평균값
min(int[] array) : 배열에서 최소값
max(int[] array) : 배열에서 최대값
요구사항
MathArrayUtils은 객체를 생성하지 않고 사용
package static2.ex;
public class MathArryUtilsMain {
public static void main(String[] args) {
int[] values = {1, 2, 3, 4, 5};
System.out.println("sum = " + MathArryUtils.sum(values));
System.out.println("average = " + MathArryUtils.average(values));
System.out.println("min = " + MathArryUtils.min(values));
System.out.println("max = " + MathArryUtils.max(values));
}
}
생성자를 호출하지 않기때문에 private로 생성자를 숨기고
main에 import를 선언
package static2.ex;
import static static2.ex.MathArryUtils.*;
public class MathArryUtilsMain {
public static void main(String[] args) {
int[] values = {1, 2, 3, 4, 5};
System.out.println("sum = " + sum(values));
System.out.println("average = " + average(values));
System.out.println("min = " + min(values));
System.out.println("max = " + max(values));
}
}
package static2.ex;
public class MathArryUtils {
private MathArryUtils() {
// 인스턴스 생성을 막는다
}
public static int sum(int[] values) {
int total = 0;
for(int value : values){
total += value;
}
return total;
}
public static double average(int[] values) {
return (double)sum(values) / values.length;
}
public static int min(int[] values) {
int minvalue = values[0];
for (int value : values) {
if (value < minvalue) {
minvalue = value;
}
}
return minvalue;
}
public static int max(int[] values) {
int maxvalue = values[0];
for (int value : values) {
if (value > maxvalue) {
maxvalue = value;
}
}
return maxvalue;
}
}