대원칙: 자바는 항상 변수의 값을 복사해서 대입한다.
변수에 값을 대입하는 것 = 변수에 들어있는 값을 복사해서 대입하는 것
기본형 | 참조형 |
값을 직접 저장 | 참조(주소)를 저장 |
산술연산 o | 산술연산 x |
null 할당 x | null 할당 o |
메서드 호출시 내부에서 값을 변경해도 호출자의 변수값 영향 없음 | 메서드 호출시 내부에서 값 변경하면 호출자의 객체도 변경 |
문제 : 상품 주문 시스템 개발 - 사용자 입력
package ref.ex;
import com.sun.source.tree.WhileLoopTree;
import java.util.Scanner;
public class ProductOrderMain3 {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("입력할 주문의 개수를 입력하세요: ");
int number=scan.nextInt();
//여러 상품의 주문 정보를 담는 배열 생성
ProductOrder [] o=new ProductOrder[number];
//createOrder()를 여러번 사용해서 상품 주문 정보들을 생성하고 배열에 저장
for(int i=0; i<o.length; i++){
System.out.println((i+1)+"번째 주문 정보를 입력하세요.");
System.out.print("상품명: ");
String productName=scan.next();
System.out.print("가격: ");
int price=scan.nextInt();
System.out.print("수량: ");
int quantity=scan.nextInt();
o[i]=createOrder(productName,price,quantity);
}
//printOrders()를 사용해서 상품 주문정보 출력
printOrders(o);
//getTotalAmount()를 사용해서 총 결재 금액 계산
int totalSum=getTotalAmount(o);
System.out.println("총 결재 금액: "+totalSum);
//총 결재 금액 출력
}
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 a:orders){
System.out.println("상품명: "+a.productName+", 가격: "+a.price+", 수량: "+a.quantity);
}
}
static int getTotalAmount(ProductOrder[] orders){
int sum=0;
for(ProductOrder b:orders){
sum+=b.price*b.quantity;
}
return sum;
}
}
'Study > 김영한의 실전자바' 카테고리의 다른 글
[김영한 실전자바]-기본편 섹션7. 접근 제어자 & 문제풀이 (0) | 2025.06.14 |
---|---|
[김영한의 실전자바] -기본편 섹션 5. 생성자 & 문제풀이 (1) | 2025.06.12 |
[김영한의 실전자바] -기본편 섹션 4. 객체지향 프로그래밍 & 문제풀이 (0) | 2025.06.10 |
[김영한의 실전 자바] -기본편 섹션 2. 클래스와 데이터 문제풀이 (1) | 2025.06.01 |
[김영한의 실전 자바] - 기본편 섹션 2. 클래스와 데이터 (0) | 2025.06.01 |