C#/수업내용

2020.04.16. 수업내용 - 장바구니 (장바구니 클래스, 과일 클래스)

dev_sr 2020. 4. 16. 22:12

 

1. App class

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_010
{
    class App
    {
        public App()
        {
           
            ShoppingBag shoppingBag = new ShoppingBag();
 
            shoppingBag.AddFruit(new Fruit("사과"));
            shoppingBag.AddFruit(new Fruit("바나나"));
            shoppingBag.AddFruit(new Fruit("복숭아"));
 
            shoppingBag.PrintList();
 
 
        }
    }
}
 
 

 

 

 

2. Inventory class

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_010
{
    class ShoppingBag
    {
        Fruit[] arrfruits;
        int index;
        public ShoppingBag()
        {
            //장바구니에는 총 5개까지 담을 수 있다.
            this.arrfruits = new Fruit[5];
        }
 
        //과일담기 기능
        public void AddFruit(Fruit fruit)
        {
            if(this.index>arrfruits.Length)
            {
                Console.WriteLine("장바구니가 꽉찼습니다");
                return;
            }
 
            this.arrfruits[this.index] = fruit;
            Console.WriteLine("장바구니에 {0}를 담았습니다."this.arrfruits[index].name);
            index++;
            
        }
 
        //목록 출력하기 기능
        public void PrintList()
        {
            Console.WriteLine("\n장바구니에 담긴 과일들 목록");
            Console.WriteLine("-------------------------------");
 
            for(int i=0; i<arrfruits.Length; i++)
            {
                int index = i;
                if(arrfruits[index] ==null)
                {
                    return;
                }
                else
                {
                    Console.WriteLine("{0},{1},{2}", index,arrfruits[index],arrfruits[index].name);
                }
            }
        }
 
    }
}
 
 

 

 

 

3. Fruit class

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_010
{
    class Fruit
    {
        public string name;
        public Fruit(string name)
        {
            this.name = name;
        }
    }
}
 
 

 

 

4. 결과값