아카이브
배열연습 인벤토리 본문
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace LearnDotnet
{
internal class App
{
//생성자
public App()
{
//인벤토리 변수 인벤토리 정의
Inventory inven;
//인벤토리 인스턴스 생성 후 변수에 할당
inven = new Inventory(5);
//아이템 인스턴스 생성 후 인벤토리에 넣기
inven.AddItem(new Item("장검"));
inven.AddItem(new Item("단검"));
inven.AddItem(new Item("활"));
//인벤토리에 모든 아이템 출력
inven.PrintAllItem();
//아이템 검색
string searchName = "활";
Item item = inven.GetItemByName(searchName);
if(item != null)
{
Console.WriteLine("{0}을 꺼냈습니다.", item.name);
}
else
{
Console.WriteLine("{0}을 찾을 수 없습니다.", searchName);
}
//다시출력
inven.PrintAllItem();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LearnDotnet
{
internal class Inventory
{
int capacity; //최대 수용량
Item[] items; //아이템 배열 번수 정의
int index;
public Inventory(int capacity)
{
this.capacity = capacity; //아이템 그룹화, 관리
items = new Item[this.capacity];
}
//메서드 정의
//아이템 넣기
public void AddItem(Item item)
{
Console.WriteLine(">> {0}", item.name);
//배열의 index 요소에 값 넣기
//요소에 접근하려면 index로 접근
//인덱스는 0 ~ (length - 1)
//this.index = this.capacity - 1;
this.items[index] = item;
index++;
}
//아이템 이름으로 검색해서 가져오기
public Item GetItemByName(string searchName)
{
Item foundItem = null;
//배열의 모든 요소(Item)의 이름 출력
for (int i = 0; i < this.items.Length; i++)
{
Item item = this.items[i];
if(item.name != null)
{
Console.WriteLine("아이템 이름: {0}, 찾는 아이템: {1}", item.name, searchName);
if(item.name == searchName)
{
Console.WriteLine("찾았습니다.");
this.items[i] = null;
foundItem = item;
break;
}
}
}
return foundItem;
}
//모든 아이템 출력하기
public void PrintAllItem()
{
for(int i = 0; i < this.items.Length; i++)
{
Item item = this.items[i];
if(item == null)
{
Console.WriteLine("[ ]");
}
else
{
Console.WriteLine(item.name);
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LearnDotnet
{
public class Item
{
public string name;
public Item(string name)
{
this.name = name;
}
}
}