오류 코드
public Product outputProduct(Product product){
for(int i = 0; i < products.length; i++){
if (products[i] instanceof Product){
return products[i];
}
}
return null;
}
결과
무조건 0번 인덱스의 객체가 반환됨
문제점
내가 의도한 바는 다형성을 이용해서 product 객체 자리에 TigerDoll, BearDoll, AirPod 3가지 중 한가지 클래스의 객체를 넣었다고 가정 했을 때 instanceof는 Product로 인식하는게 아니라 3가지 클래스 중 하나로 인식한다고 생각함
하지만 그냥 Product를 인식해서 3가지다 Product로 바라볼 수 있기 때문에 무조건 if문 만족함
수정
public Product outputProduct(int choice) {
switch (choice) {
case TIGERDOLL :
if (TigerDoll.count == 0) {
System.out.println("상품이 존재하지 않습니다.");
return null;
}
for (int i = 0; i < products.length; i++) {
if (products[i] instanceof TigerDoll ) {
if (products[i].resist()) {
TigerDoll.count--;
count--;
return products[i];
} else {
return null;
}
}
}
case BEARDOLL :
for (int i = 0; i < products.length; i++) {
if (products[i] instanceof BearDoll ) {
if (products[i].resist()) {
BearDoll.count--;
count--;
return products[i];
} else {
return null;
}
}
}
case AIRPOD :
...
... 생략
결과
됨
해결 방법
매개변수로 객체를 받아 오는게 아니라 선택한 번호를 받아와서 switch 문을 만들고 각 케이스일때 products 배열 안에서 원하는 상품을 찾게함
'error note > Java' 카테고리의 다른 글
nextInt() 이후 nextLine()에서 공백 입력 (0) | 2024.04.22 |
---|---|
반복문 + if문 오류 (0) | 2024.04.22 |
자바 369 게임 만들기 오류 (0) | 2024.04.20 |