[요구사항]
CustomClass
- 고객번호, 이름, 나이 필드 선언
- addToCart(), purchase() 메소드를 통해 장바구니에 담고 결제하기
+ 이후 ProductClass타입의 shopingBasket 필드 선언 -> addToCart()에서 매개변수로 받은 객체를 배열에 담기 위함
ProductClass
- 물품번호, 이름, 가격, 수량 필드 선언
🚫 트러블 슈팅 🤕
1. 객체 타입을 배열에 담기
배우면서 기본 타입이나 String 타입으로만 배열에 담았기 때문에 객체 타입으로 담는 방식이 생각이 안났다.
생성자를 통해 main()에서 shopingBasket을 초기화 해주는 부분까지는 했지만, addToCart()메소드에서 어떻게 담으라는 건지 이해가 안됐다 . .
void addToCart(ProductClass product) {}
처음에 매개변수로 객체 타입만 받아왔을 때는 shopingBasket = product; 를 통해 배열에 담을 수 있었다.
그러나 우리가 배열에 담아야 할 것은 product객체와 고객이 입력한 수량이다.
void addToCart(ProductClass product, int quantity) {}
즉, ProductClass 타입의 객체와 int 타입을 ProductClass[] shopingBasket에 넣어야 한다. .
💥여기서 헷갈린 부분이 다른 타입의 변수를 배열에 어떻게 넣느냐 였다.
shoppingBasket[i] = new ProductClass(product.id, product.name, product.price, quantity);
🔵 다른 타입의 두 변수를 ProductClass 타입의 배열에 담기 위해서는 ProductClass 객체를 생성해주면 되는 것이었다..!
👆 c1.addToCart(p1, 8); 을 입력했을 때 고객이 입력한 객체물품과 수량이 출력되는 것을 확인할 수 있다.
2. addToCart() 메소드에 for문을 돌려서 호출될 때마다 저장하면 안되는가?
처음 생각은 사용자가 c1.addToCart(p1, 8); 메소드를 호출할 때마다 for문을 돌려 배열에 저장되게 하고 싶었다.
for(int i = 0; i < shoppingBasket.length; i++) {
shoppingBasket[i] = new ProductClass(product.id, product.name, product.price, quantity);
product.quantity -= quantity;
System.out.printf("%s님이 %s 상품을 %d개 장바구니에 담았습니다. \n", this.name, shoppingBasket[i].name, shoppingBasket[i].quantity);
System.out.printf("%s상품의 남은 수량: %d \n", shoppingBasket[i].name, product.quantity);
break;
}
그러나 for문을 돌리게 되면 메소드를 호출할 때마다 i가 초기화되기 때문에 값이 index[0]에 덮어씌워지는 문제가 발생했다.
(처음에는 콘솔창에 내가 미리 초기화한 [10]개 이상이 출력되길래 무한개 저장되는 줄 알았는데 index[0]에 계속 덮어씌워지고 있었던 것이다. .)
if(quantity < product.quantity) {
int i = 0;
// ProductClass타입의 배열에 담기 위해 ProductClass 객체를 생성한 후 담아야 함
shoppingBasket[i] = new ProductClass(product.id, product.name, product.price, quantity);
product.quantity -= quantity;
System.out.println("==============================================================");
System.out.printf("[%d] %s님이 %s 상품을 %d개 장바구니에 담았습니다. \n", i, this.name, shoppingBasket[i].name, shoppingBasket[i].quantity);
System.out.printf("%s상품의 남은 수량: %d \n", shoppingBasket[i].name, product.quantity);
i++;
} else {
System.out.println("수량을 초과하였습니다.");
}
이때까지도 초기화에 대한 이해를 하지 못하고 있었던 게 for문도 어떻게 보면 초기화 문제로 계속 덮어씌워지고 있었던 것인데, int i = 0;을 통해 다시 초기화를 시키다니 . . 😂
저렇게 되면 메소드를 호출할 때마다 또 int i = 0;을 통해 0으로 초기화되어서 덮어씌워지는 문제가 반복될텐데 말이다.
🔵 따라서, int i;를 전역으로 빼서 메소드를 나갈 때 i++;를 통해 재정의를 하여 덮어쓰는 문제를 해결할 수 있었다.
3. java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 에러발생
덮어씌워지는 문제를 해결하니까 이제는 index 초과된다고 오류가 뜨네 . .
이는 index 초과시 별도의 예외처리를 하지 않아서 오류가 발생한 것이다.
try {
// 고객이 입력한 수량과 상품에 저장된 수량 비교
if(quantity < product.quantity) {
// ProductClass타입의 배열에 담기 위해 ProductClass 객체를 생성한 후 담아야 함
shoppingBasket[i] = new ProductClass(product.id, product.name, product.price, quantity);
product.quantity -= quantity;
System.out.println("==============================================================");
System.out.printf("[%d] %s님이 %s 상품을 %d개 장바구니에 담았습니다. \n", i, this.name, shoppingBasket[i].name, shoppingBasket[i].quantity);
System.out.printf("%s상품의 남은 수량: %d \n", shoppingBasket[i].name, product.quantity);
i++;
} else {
System.out.println("수량을 초과하였습니다.");
}
} catch (Exception e) {
System.out.println("장바구니에 담을 수 없습니다. " + e);
}
🔵 try - catch문으로 해결 완료!
➰ try { 예외발생할 가능성이 있는 문장 } catch(Exeption e) { Exeption이 발생했을 경우 이를 처리할 문장을 적는 곳 }으로 사용하면 된다.