반응형
SMALL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study08
{
class Inventory
{
private int capacity; //최대 용량
private Item[] items; //아이템들을 관리 배열
int index;
//생성자
public Inventory(int capacity)
{
this.capacity = capacity;
//배열 초기화
this.items = new Item[this.capacity];
}
public void AddItem(Item item)
{
for (int i = 0; i < items.Length; i++)
{
if (items[i] == null)
{
Console.WriteLine("{0} 을(를) 인벤토리에 넣었습니다.", item.name);
items[i] = item;
break;
}
else if (items[i].name == item.name)
{
Console.WriteLine("{0} 은(는) 이미 인벤토리에 있습니다..", item.name);
break;
}
}
}
public int GetItemCount()
{
index = 0;
//배열이 가지고있는 아이템의 갯수
foreach (Item item in items)
{
if (item != null)
{
index++;
}
else continue;
}
return index;
}
public Item GetItemByName(string searchName)
{
Item wantItem = null; //변수를 지정해 줘야 if문 이후에 break 되기전 if변수에 할당한 값을 return 가능하더라
for (int i = 0; i < items.Length; i++)
{
if (items[i].name == searchName)
{
wantItem = this.items[i];
this.items[i] = null;
break;
}
}
return wantItem;
//배열을 순회하며 아이템이 있을경우
//아이템의 이름과 searchName이 같으면
//해당 아이템을 반환
//배열의 요소를 비워줘야함
//빈공간이 있다면 정렬 해야함
}
public void PrintAllItems()
{
for (int i = 0; i < this.items.Length; i++)
{
string str = "";
if (this.items[i] == null)
str = "[ ]";
else
str = this.items[i].name;
Console.WriteLine(str);
}
}
public void Arrange()
{
for(int i = 0; i < items.Length; i++)
{
if(items[i] != null)
{
for (int j = 0; j <= i; j++)
{
items[j] = items[i];
items[i] = null;
break;
}
}
}
}
}
}
- 클래스 반환하는데에서 아직도 조금 헷갈림이 있었음. (public Item GetItemByName 매서드 사용시 어떤 타입의 값을 반환해 주어야 하는지 부터 정리할 필요 있음) - 보강필요
- for문으로 배열 입력 내용 출력시 null 값인 배열의 인덱스에 원하는 종류의 값을 넣고 싶다면 for문 혹은 foreach문 밖에서 변수를 지정한 뒤 사용하는 방법또한 좀더 연습이 필요해 보임 (public void PrintAllItems() 매서드 사용시)
결과물
반응형
LIST
'C# > 수업 과제' 카테고리의 다른 글
Jason 직렬화 역직렬화 과제 (0) | 2023.01.12 |
---|---|
List<T> 와 프로퍼티, 상속을 이용한 인벤토리 과제 (0) | 2023.01.10 |
Class 메서드를 이용한 스타크래프트 유닛 인스턴스 만들기 (0) | 2023.01.05 |
라바 to 히드라 to 럴커(클래스 메서드 사용) (0) | 2023.01.05 |
캐릭터 Class 만들어오기 (0) | 2023.01.04 |