푸들푸들

[JAVA] 변수와 초기화 본문

SELF-STUDY

[JAVA] 변수와 초기화

COCO_develop 2025. 3. 25. 23:02

변수의 종류

멤버 변수: 클래스에 선언

지역 변수: 메서드에 선언, 매개변수도 지역 변수의 한 종류

 public class Student {
     String name;
     int age;
     int grade;
 }

-> name, age, grade = 멤버 변수

 public class ClassStart3 {
     public static void main(String[] args) {
         Student student1;
                student1 = new Student();
         Student student2 = new Student();
    }
 }

-> student1, student2 = 지역 변수

 

변수의 값 초기화

멤버 변수: 자동 초기화, 숫자(int)=0, boolean=false, 참조형=null

지역 변수: 수동 초기화

 

 

null

= 값이 존재하지 않음

참조형 변수에서 아직 가리키는 대상이 없을 때

GC(Garbage Collection): 참조하는 곳이 모두 사라진 객체는 JVM이 필요없는 객체로 판단하고 GC를 사용해 제거함

 

NullPointerException

객체를 참조할 때 -> .(dot) 사용

null. -> java.lang.NullPointerException

 

 

 

예제1

package ref.ex;
public class ProductOrderMain2 {
    public static void main(String[] args) {
        // 여러 상품의 주문 정보를 담는 배열 생성
        // createOrder()를 여러번 사용해서 상품 주문 정보들을 생성하고 배열에 저장
        // printOrders()를 사용해서 상품 주문 정보 출력
        // getTotalAmount()를 사용해서 총 결제 금액 계산
        // 총 결제 금액 출력
    }
 }

--> 답

// 원래 코드
public class ProductOrderMain {
    public static void main(String[] args) {
        ProductOrder[] orders = new ProductOrder[3];

        ProductOrder order1 = new ProductOrder();
        order1.productName = "두부";
        order1.price = 2000;
        order1.quantity = 2;
        orders[0] = order1;

        ProductOrder order2 = new ProductOrder();
        order2.productName = "김치";
        order2.price = 5000;
        order2.quantity = 1;
        orders[1] = order2;

        ProductOrder order3 = new ProductOrder();
        order3.productName = "콜라";
        order3.price = 1500;
        order3.quantity = 2;
        orders[2] = order3;

        int totalAmount = 0;
        for (ProductOrder o : orders) {
            System.out.println("상품명: " + o.productName + ", 가격: " + o.price + ", 수량: " + o.quantity);
            totalAmount += o.price * o.quantity;
        }
        System.out.println("총 결제 금액: " + totalAmount);
    }
}

/***** 리팩토리 *****/
public class ProductOrderMain2 {
    public static void main(String[] args) {
        ProductOrder[] orders = new ProductOrder[3];

        orders[0] = createOrder("두부", 2000, 2);
        orders[1] = createOrder("김치", 5000, 1);
        orders[2] = createOrder("콜라", 1500, 2);

        printOrders(orders);
        int totalAmount = getTotalAmount(orders);
        System.out.println("총 결제 금액: " + totalAmount);
    }

    static ProductOrder createOrder(String productName, int price, int quantity){
        ProductOrder order = new ProductOrder();
        order.productName = productName;
        order.price = price;
        order.quantity = quantity;
        return order;
    }

    static void printOrders(ProductOrder[] orders){
        for (ProductOrder order : orders) {
            System.out.println("상품명: " + order.productName + ", 가격: " + order.price + ", 수량: " + order.quantity);
        }
    }

    static int getTotalAmount(ProductOrder[] orders){
        int totalAmount = 0;
        for (ProductOrder order : orders) {
            totalAmount += order.price * order.quantity;
        }
        return totalAmount;
    }
}

 

 

예제2

--> 답

public class ProductOrderMain2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("입력할 주문의 개수를 입력하세요: ");
        int n = scanner.nextInt();
        scanner.nextLine();

        ProductOrder[] orders = new ProductOrder[n];
        for (int i = 0; i < orders.length; i++) {
            System.out.println((i + 1) + "번째 주문 정보를 입력하세요.");
            System.out.print("상품명: ");
            String productName = scanner.nextLine();
            System.out.print("가격: ");
            int price = scanner.nextInt();
            System.out.print("수량: ");
            int quantity = scanner.nextInt();
            scanner.nextLine(); // 입력 버퍼를 비우기 위한 코드
            orders[i] = createOrder(productName, price, quantity);
        }
        printOrders(orders);
        int totalAmount = getTotalAmount(orders);
        System.out.println("총 결제 금액: " + totalAmount);
    }

    static ProductOrder createOrder(String productName, int price, int quantity){
        ProductOrder order = new ProductOrder();
        order.productName = productName;
        order.price = price;
        order.quantity = quantity;
        return order;
    }

    static void printOrders(ProductOrder[] orders){
        for (ProductOrder order : orders) {
            System.out.println("상품명: " + order.productName + ", 가격: " + order.price + ", 수량: " + order.quantity);
        }
    }

    static int getTotalAmount(ProductOrder[] orders){
        int totalAmount = 0;
        for (ProductOrder order : orders) {
            totalAmount += order.price * order.quantity;
        }
        return totalAmount;
    }
}

'SELF-STUDY' 카테고리의 다른 글

[JAVA] 생성자  (0) 2025.04.03
[JAVA] 절차 지향, 객체 지향 프로그래밍  (2) 2025.03.26
[JAVA] 기본형, 참조형  (0) 2025.03.25
[JAVA] 클래스, 객체  (0) 2025.03.20
[IntelliJ] Window 단축키  (0) 2025.03.13