본문 바로가기
C#/수업내용

[C# 6일차] 배열을 이용한 Inventory 저장, 찾기, 삭제

by 왹져박사 2023. 1. 8.
728x90

App Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Day6
{
    class App
    {
        //생성자
        public App()
        {
            Console.WriteLine("App 생성자");
            Console.WriteLine();

            Inventory inventory = new Inventory();

            inventory.AddItem(new Item("장검"));      //장검 저장
            inventory.AddItem(new Item("단검"));      //단검 저장
            inventory.AddItem(new Item("지팡이"));     //지팡이 저장


            inventory.PrintItems();     //인벤토리에 저장된 아이템 출력
            Console.WriteLine();       

            inventory.FindItemByName("장검");     //"장검"이 인벤토리에 존재하는지 검사
            Console.WriteLine();

            inventory.FindItemByName("지팡이");    //"지팡이"가 인벤토리에 존재하는지 검사
            Console.WriteLine();

            inventory.DeleteItem("단검");             //단검을 인벤토리에서 삭제
            inventory.PrintItems();                    //인벤토리에 저장된 아이템 출력
            inventory.AddItem(new Item("지팡이"));     //지팡이 저장


        }
    }
}

 

Item Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Day6
{
    class Item
    {
        public string name;
        //생성자
        public Item(string name)
        {
            this.name = name;
        }
    }
}

 

Inventory Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Day6
{
    class Inventory
    {
        Item[] items;

        int index = 0;

        //생성자
        public Inventory()
        {
            items = new Item[2];        //용량이 2인 인벤토리 
        }
        public void AddItem(Item item)          //아이템 저장
        {
            //배열(items)에 매개변수로 전달받은 Item을 저장
            if (index > items.Length - 1)
            {
                Console.WriteLine("인벤토리에 공간이 없습니다. ");
            }
            else if (items[index] == null)
            {
                items[index] = item;
                Console.WriteLine("{0} 아이템이 인벤토리에 저장되었습니다. ", items[index].name);

                index++;
            }
        }

        public void PrintItems()            //인벤토리에 저장된 아이템 출력
        {
            //for, foreach를 사용해서 items의 요소들의 이름을 출력
            for (int i = 0; i < items.Length; i++)
            {
                if (items[i] != null)
                {
                    Console.WriteLine(items[i].name);
                }
            }

            //foreach (Item item in items)
            //{
            //    if (item != null)
            //    {
            //        Console.WriteLine(item.name);
            //    }
            //}

        }
        public Item FindItemByName(string name)         //아이템이 인벤토리에 존재하는지 검사
        {
            Item foundItem = null;

            //문자열 이름으로 아이템을 찾는 메서드를 작성하세요
            for (int i = 0; i < items.Length; i++)
            {
                if (items[i] != null && items[i].name == name)
                {
                    foundItem = items[i];
                    Console.WriteLine("{0}이(가) 존재합니다. ", name);
                    break;
                }
                else
                {
                    //출력하니 배열의 크기(n)만큼 검색하여 n번 출력됨. 
                    //처음에 잘못된 출력으로 인식될 수 있어 인벤토리이 n번째 칸에 존지하지 않는다는 것 또한 알림
                    Console.WriteLine("{0}이(가) {1}번칸에 존재하지 않습니다. ", name, i+1);

                    //혹은 아래처럼 처리할 수 있을 듯하다
                    if (i == items.Length - 1)
                    {
                        Console.WriteLine("{0}이(가) 존재하지 않습니다. ", name);
                    }
                }
            }

            return foundItem;          //Item 타입이기 때문에 반드시 Item 타입의 값을 리턴해야 함!!!
        }

        public void DeleteItem(string name)             //아이템 삭제
        {
            for (int i = 0; i < items.Length; i++)
            {
                if (items != null && items[i].name == name)
                {
                    Console.WriteLine("{0}을(를) 버렸습니다. ", name);
                    items[i] = null;
                    index = i;
                    break;
                }
            }
        }
    }
}

 

FindItemByName 메서드에서 Item 타입의 값을 반환해야 하는 부분은 인지하고 있었다.

하지만 새로운 지역변수를 만들고 그 값을 리턴한다는 생각까지는 처음에 하지 못해 어렵게 느껴졌다.!!

 

실행 결과

728x90