'전체 글'에 해당되는 글 142건

  1. 2019.10.01 10.01 커맨드센터에서 SCV1,2를 만들고 공격하기
  2. 2019.10.01 10.01 여러 class를 이용해 햄버거 세트 만들기
  3. 2019.09.27 워크래프트 캐릭생성하기
  4. 2019.09.27 성적표만들기
  5. 2019.09.27 String.Format을 이용하지않은 중앙정렬
  6. 2019.09.27 한글과 영문,숫자의 바이트 인식
  7. 2019.09.27 더하기 사이클
  8. 2019.09.26 switch 문

10.01 커맨드센터에서 SCV1,2를 만들고 공격하기

C#/실습 2019. 10. 1. 16:49

예제:

코드:

Program.cs:
namespace _10._01_step2
{
    class Program
    {
        static void Main(string[] args)
        {
            new App();//App타입 객체를 생성하고 App()이라는 메소드를 호출한다
        }
    }
}

 

App.cs:

namespace _10._01_step2
{
    class App
    {
        public App()
        {
            CommandCenter commandCenter1 = new CommandCenter();
            Console.WriteLine(commandCenter1 + "가 생성되었습니다.");
            Unit unit1 = commandCenter1.MakeUnit("SCV1");
            Unit unit2 = commandCenter1.MakeUnit("SCV2");
            unit1.Attack(unit2);
        }
    }
}

CommandCenter.cs:

namespace _10._01_step2
{
    class CommandCenter
    {
        int hp;

        public CommandCenter()
        {

        }
        public Unit MakeUnit(string name)
        {
            Unit unit = new Unit();
            unit.name = name;
            Console.WriteLine(unit.name + "이 생성되었습니다.");
            return unit;
        }
    }
}

Unit.cs:

using System;

namespace _10._01_step2
{
    class Unit
    {
        //데이터
        public string name;
        int hp =100;
        int maxHp = 100;
        int damage=5;
        public Unit()
        {

        }
        //메서드
        //이동한다
        public void Move()
        {

        }
        public void Attack(Unit unit)
        {
            Console.WriteLine($"{this.name}이{unit.name}에게 {damage}만큼의 피해를 입혔습니다.");
            unit.GetHit(this.damage);
        }
        public void GetHit(int damage)
        {
            this.hp = this.hp - damage;
            Console.WriteLine($"{this.name}이 {damage}만큼의 피해를 입었습니다.");
            Console.WriteLine(this.hp + "/" + this.maxHp);
        }
    }
}

'C# > 실습' 카테고리의 다른 글

10.02 버거세트  (0) 2019.10.02
10.02 커피상점  (0) 2019.10.02
10.01 여러 class를 이용해 햄버거 세트 만들기  (0) 2019.10.01
워크래프트 캐릭생성하기  (0) 2019.09.27
switch 문  (0) 2019.09.26
:

10.01 여러 class를 이용해 햄버거 세트 만들기

C#/실습 2019. 10. 1. 16:45

세트로 만들지 여부 확인
Set 클라스의 인스턴스를 이용해 메뉴를 한 클라스에 묶는다.

Program.cs:

namespace _10._01_step4
{
    class Program
    {
        static void Main(string[] args)
        {
            new App();
        }
    }
}

App.cs:

using System;


namespace _10._01_step4
{
    class App
    {
        public App()
        {
            BurgerShop burgerShop1 = new BurgerShop();
burgerShop1.name = "McDonalds";
            Console.WriteLine("버거를 입력해주세요: ");
            Burger burger1 = burgerShop1.MakeBurger(Console.ReadLine());
            Console.WriteLine("사이드메뉴를 입력해주세요");
            PotatoChip potatoChip1 = burgerShop1.MakePotatoChip(Console.ReadLine());
            Console.WriteLine("음료를 입력해주세요");
            Drink drink1 = burgerShop1.MakeDrink(Console.ReadLine());
            Console.WriteLine(burger1.name + "이(가) 생성되었습니다.");
            Console.WriteLine(potatoChip1.name + "이 생성되었습니다.");
            Console.WriteLine(drink1.name + "이 생성되었습니다.");
            Console.WriteLine("세트로 만드시겠습니까?(1.예, 2.아니오)");
            string input = Console.ReadLine();
            if (input == "1")
            {
                Set set1 = burgerShop1.MakeSet(burger1, potatoChip1, drink1);
                Console.WriteLine("세트(" + set1.burger.name + "," + set1.drink.name + "," + set1.potatochip.name + ")이 생성되었습니다.");
            }
            else if (input=="2")
            {

            }

        }
    }
}

BurgerShop.cs:

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

namespace _10._01_step4
{
    class BurgerShop
    {
        public string name;
        public BurgerShop()
        {

        }
        public Burger MakeBurger(string name)
        {
            Burger burger = new Burger();
            burger.name = name;
            return burger;
        }
        public PotatoChip MakePotatoChip(string name)
        {
            PotatoChip potatoChip = new PotatoChip();
            potatoChip.name = name;
            return potatoChip;
        }
        public Drink MakeDrink(string name)
        {
            Drink drink = new Drink();
            drink.name = name;
            return drink;
        }
        public Set MakeSet(Burger burger, PotatoChip potatochip, Drink drink)
        {
            Set newSet = new Set();
            newSet.burger = burger;
            newSet.potatochip = potatochip;
            newSet.drink = drink;
            return newSet;
        }
    }
}

Burger.cs:

namespace _10._01_step4
{
    class Burger
    {
        public string name;
        public Burger()
        {
            
        }
    }
}

Drink.cs:

namespace _10._01_step4
{
    class Drink
    {
        public string name;
        public Drink()
        {

        }
    }
}

PotatoChip.cs:

namespace _10._01_step4
{
    class PotatoChip
    {
        public string name;
        public PotatoChip()
        {

        }
    }
}

Set.cs:

namespace _10._01_step4
{
    class Set
    {
        public Burger burger;
        public PotatoChip potatochip;
        public Drink drink;
        public Set()
        {

        }
    }
}

'C# > 실습' 카테고리의 다른 글

10.02 커피상점  (0) 2019.10.02
10.01 커맨드센터에서 SCV1,2를 만들고 공격하기  (0) 2019.10.01
워크래프트 캐릭생성하기  (0) 2019.09.27
switch 문  (0) 2019.09.26
09.24 최대공약수 구하기  (0) 2019.09.24
:

워크래프트 캐릭생성하기

C#/실습 2019. 9. 27. 17:04

진영

얼라이언스, 호드 

 

종족 

얼라이언스 

인간, 드워프 

 

호드 

오크, 언데드 

 

직업 

인간 : 흑마법사, 사제 

드워프 : 수도사, 사냥꾼 

오크 : 죽음의 기사, 전사 

언데드 : 마법사, 도적, 

 

[얼라이언스, 호드 ] 진영을 선택해 주세요. 얼라이언스 

[인간, 드워프 ] 종족을 선택해주세요:인간 

[흑마법사, 사제] 직업을 선택해주세요. 사제 

얼라이언스, 인간, 사제 입니다.

 

코드

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _09._27_step4
{
    class Program
    {
        enum Team { alliance, horde }
        enum Races { human, dwarf, orc, undead, }
        enum Classes { warlock, priest, monk, hunter, death_knight, warrior, mage, rogue }
 
        static void Main(string[] args)
        {
            int inputint;
            Console.WriteLine("[1,얼라이언스] [2,호드]");
            Console.WriteLine("진영을 선택해주세요: ");
            inputint = int.Parse(Console.ReadLine());
            Team choosenTeam = (Team)(inputint - 1);
            switch (choosenTeam)
            {
                case Team.alliance:
                    
                    { 
                        Console.WriteLine("[1,인간] [2,드워프]");
                        Console.WriteLine("종족을 선택해주세요:");
                        inputint = int.Parse(Console.ReadLine());
                        Races choosenRace = (Races)(inputint - 1);
                        switch (choosenRace)
                        {
                            case Races.human:
                                { 
                                    Console.WriteLine("[1,흑마법사] [2,프리스트]");
                                    Console.WriteLine("직업을 선택해주세요: ");
                                    inputint = int.Parse(Console.ReadLine());
                                    Classes choosenClass = (Classes)(inputint - 1);
                                    switch (choosenClass)
                                    {
                                        case Classes.warlock:
                                            Console.WriteLine("나의 캐릭터:");
                                            Console.WriteLine($"진영: {choosenTeam}, 종족: {choosenRace}, 직업: {choosenClass}");
                                            break;
                                        case Classes.priest:
                                            Console.WriteLine("나의 캐릭터:");
                                            Console.WriteLine($"진영: {choosenTeam}, 종족: {choosenRace}, 직업: {choosenClass}");
                                            break;
                                    }
                                    break;
                                }
 
                            case Races.dwarf:
                                { 
                                    Console.WriteLine("[1,수도사] [2,사냥꾼]");
                                    Console.WriteLine("직업을 선택해주세요: ");
                                    inputint = int.Parse(Console.ReadLine());
                                    Classes choosenClass = (Classes)(inputint + 1);
                                    switch (choosenClass)
                                    {
                                        case Classes.monk:
                                            Console.WriteLine("나의 캐릭터:");
                                            Console.WriteLine($"진영: {choosenTeam}, 종족: {choosenRace}, 직업: {choosenClass}");
                                            break;
                                        case Classes.hunter:
                                            Console.WriteLine("나의 캐릭터:");
                                            Console.WriteLine($"진영: {choosenTeam}, 종족: {choosenRace}, 직업: {choosenClass}");
                                            break;
                                    }
                                    break;
                                }
                        }
                        break;
                    }
                    
 
                case Team.horde:
                    { 
                        Console.WriteLine("[1,오크] [2,언데드]");
                        Console.WriteLine("종족을 선택해주세요:");
                        inputint = int.Parse(Console.ReadLine());
                        Races choosenRace = (Races)(inputint + 1);
                        switch (choosenRace)
                        {
                            case Races.orc:
                                { 
                                    Console.WriteLine("[1,죽음의 기사] [2,전사]");
                                    Console.WriteLine("직업을 선택해주세요: ");
                                    inputint = int.Parse(Console.ReadLine());
                                    Classes choosenClass = (Classes)(inputint + 3);
                                    switch (choosenClass)
                                    {
                                        case Classes.death_knight:
                                            Console.WriteLine("나의 캐릭터:");
                                            Console.WriteLine($"진영: {choosenTeam}, 종족: {choosenRace}, 직업: {choosenClass}");
                                            break;
                                        case Classes.warrior:
                                            Console.WriteLine("나의 캐릭터:");
                                            Console.WriteLine($"진영: {choosenTeam}, 종족: {choosenRace}, 직업: {choosenClass}");
                                            break;
                                    }
                                    break;
                                }
                            case Races.undead:
                                { 
                                    Console.WriteLine("[1,마법사] [2,도적]");
                                    Console.WriteLine("직업을 선택해주세요: ");
                                    inputint = int.Parse(Console.ReadLine());
                                    Classes choosenClass = (Classes)(inputint + 5);
                                    switch (choosenClass)
                                    {
                                        case Classes.mage:
                                            Console.WriteLine("나의 캐릭터:");
                                            Console.WriteLine($"진영: {choosenTeam}, 종족: {choosenRace}, 직업: {choosenClass}");
                                            break;
                                        case Classes.rogue:
                                            Console.WriteLine("나의 캐릭터:");
                                            Console.WriteLine($"진영: {choosenTeam}, 종족: {choosenRace}, 직업: {choosenClass}");
                                            break;
                                    }
                                    break;
                                }
                        }
                        break;
                    }
            }
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
:

성적표만들기

C#/Study 2019. 9. 27. 13:17

출력 :

메인화면
메인화면에서 1입력시
메인에서 2입력시
추가 페이지에서 저장하는 모습
메인에서 1을 입력후 조회 확인
다수의 데이터 조회
메인에서 3을 입력후 수정할 데이터 선택
수정할 데이터 입력
수정된 데이터 확인
메인에서 4 입력후 삭제할 데이터 선택 (4번선택)
삭제된 데이터 확인

코드

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Syntax
{
    class Program
    {
        static void Main(string[] args)
        {
            string[,] array = new string[1006];
            int keynum = 0;
            string fmt = "0000";
            string formatString = "{0,0:" + fmt + "}";
            int language = 0;
            int math = 0;
            int english = 0;
            int mean = 0;
            string datasname = null;
            string datalanguage = null;
            string datamath = null;
            string dataenglish = null;
            string strmean = null;
            float avglanguage = 0.00f;
            float avgmath = 0.00f;
            float avgenglish = 0.00f;
            float avgtotal = 0.00f;
            while (true)
            {
            Restart1:
                Console.WriteLine("1.조회");
                Console.WriteLine("2.추가");
                Console.WriteLine("3.수정");
                Console.WriteLine("4.삭제");
                Console.WriteLine("0.종료");
                string finput = Console.ReadLine();
 
                if (finput == "1")//조회
                {
                    Console.Clear();
                    Console.Write("Total Student: ");
                    Console.ForegroundColor = ConsoleColor.Blue;
                    Console.WriteLine(keynum);
                    Console.ResetColor();
                    Console.WriteLine();
                    Console.WriteLine("+----+----------------+------+------+------+------+");
                    Console.WriteLine("|번호|     학생명     | 국어 | 수학 | 영어 | 평균 |");
                    Console.WriteLine("+----+----------------+------+------+------+------+");
                    for (int i = 0; i < keynum; i++)
                    {
                        int namebytelen= Encoding.Default.GetBytes(array[i,1]).Length;
                        int padlen = 8 - (namebytelen / 2);
                        Console.Write("|");
                        Console.Write(formatString, (i + 1));
                        Console.Write("|");
                        if (namebytelen % 2 != 0)
                        {
                            Console.Write("{0}""".PadLeft(padlen) + array[i,1+ "".PadRight(padlen - 1+ "|");
                        }
                        else
                        {
                            Console.Write("{0}""".PadLeft(padlen) + array[i, 1+ "".PadRight(padlen) + "|");
                        }
                         //이름
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write(String.Format("{0,6}", array[i, 2])); //국어
                        Console.ResetColor();
                        Console.Write("|");
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write(String.Format("{0,6}", array[i, 3]));//수학
                        Console.ResetColor();
                        Console.Write("|");
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write(String.Format("{0,6}", array[i, 4]));//영어
                        Console.ResetColor();
                        Console.Write("|");
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Write(String.Format("{0,6}", array[i, 5])); //평균
                        Console.ResetColor();
                        Console.WriteLine("|");
 
                    }
                    Console.WriteLine("+----+----------------+------+------+------+------+");
                    Console.WriteLine(String.Format("|    | 전체 학생 평균 |{0,6}|{1,6}|{2,6}|{3,6}|", avglanguage.ToString("F2"), avgmath.ToString("F2"), avgenglish.ToString("F2"), avgtotal.ToString("F2"))); //전체학생평균
                    Console.WriteLine("+----+----------------+------+------+------+------+");
                } //조회
                else if (finput == "2")//추가
                {
                Restart2:
                    Console.Clear();
                    Console.Write("학생명: ");
                    datasname = Console.ReadLine();
                    Console.Write("국어: ");
                    datalanguage = Console.ReadLine();
                    Console.Write("수학: ");
                    datamath = Console.ReadLine();
                    Console.Write("영어: ");
                    dataenglish = Console.ReadLine();
                    Console.Write("위의 데이터를 저장하겠습니까? (예: 1 / 아니오 : 0) :");
                    string datasave = Console.ReadLine();
                    if (datasave == "1" && datalanguage.Length<=2 && datamath.Length <= 2 && dataenglish.Length <= 2)
                    {
                        array[keynum, 0= Convert.ToString(keynum + 1);
                        array[keynum, 1= datasname;
                        array[keynum, 2= datalanguage;
                        array[keynum, 3= datamath;
                        array[keynum, 4= dataenglish;
                        language = Convert.ToInt32(array[keynum, 2]);
                        math = Convert.ToInt32(array[keynum, 3]);
                        english = Convert.ToInt32(array[keynum, 4]);
                        mean = (language + math + english) / 3;
                        strmean = Convert.ToString(mean);
                        array[keynum, 5= strmean;
                        keynum++;
                        float sumlanguage = 0.00f;
                        float summath = 0.00f;
                        float sumenglish = 0.00f;
                        float sumtotal = 0.00f;
                        for (int i2 = 0; i2 < keynum; i2++)
                        {
                            sumlanguage = sumlanguage + Convert.ToInt32(array[i2, 2]);
                            summath = summath + Convert.ToInt32(array[i2, 3]);
                            sumenglish = sumenglish + Convert.ToInt32(array[i2, 4]);
                            sumtotal = sumtotal + Convert.ToInt32(array[i2, 5]);
                        }
                        avglanguage = sumlanguage / keynum;
                        avgmath = summath / keynum;
                        avgenglish = sumenglish / keynum;
                        avgtotal = sumtotal / keynum;
                    }
                    else if (datasave == "0")
                    {
                        goto Restart2;
                    }
                    Console.Clear();
 
                }//추가
                else if (finput == "3")//수정
                {
                    Console.Clear();
                    Console.Write("Total Student: ");
                    Console.ForegroundColor = ConsoleColor.Blue;
                    Console.WriteLine(keynum);
                    Console.ResetColor();
                    Console.WriteLine();
                    Console.WriteLine("+----+----------------+------+------+------+------+");
                    Console.WriteLine("|번호|     학생명     | 국어 | 수학 | 영어 | 평균 |");
                    Console.WriteLine("+----+----------------+------+------+------+------+");
                    for (int i = 0; i < keynum; i++)
                    {
 
                        int namebytelen = Encoding.Default.GetBytes(array[i, 1]).Length;
                        int padlen = 8 - (namebytelen / 2);
                        Console.Write("|");
                        Console.Write(formatString, (i + 1));
                        Console.Write("|");
                        if (namebytelen % 2 != 0)
                        {
                            Console.Write("{0}""".PadLeft(padlen) + array[i, 1+ "".PadRight(padlen - 1+ "|");
                        }
                        else
                        {
                            Console.Write("{0}""".PadLeft(padlen) + array[i, 1+ "".PadRight(padlen) + "|");
                        }
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write(String.Format("{0,6}", array[i, 2])); //국어
                        Console.ResetColor();
                        Console.Write("|");
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write(String.Format("{0,6}", array[i, 3]));//수학
                        Console.ResetColor();
                        Console.Write("|");
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write(String.Format("{0,6}", array[i, 4]));//영어
                        Console.ResetColor();
                        Console.Write("|");
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Write(String.Format("{0,6}", array[i, 5])); //평균
                        Console.ResetColor();
                        Console.WriteLine("|");
 
                    }
                    Console.WriteLine("+----+----------------+------+------+------+------+");
                    Console.WriteLine(String.Format("|    | 전체 학생 평균 |{0,6}|{1,6}|{2,6}|{3,6}|", avglanguage.ToString("F2"), avgmath.ToString("F2"), avgenglish.ToString("F2"), avgtotal.ToString("F2"))); //전체학생평균
                    Console.WriteLine("+----+----------------+------+------+------+------+");
                    Console.Write($"수정할 데이터 번호를 입력하세요({array[0, 0]}~{keynum}) [0 : Exit]: ");
                    int fixinput = Convert.ToInt32(Console.ReadLine());
                    if (fixinput <= keynum && fixinput != 0)
                    {
                        Console.Clear();
                        Console.Write($"기존 학생명: {array[fixinput - 1, 1]} >> ");
                        Console.ForegroundColor = ConsoleColor.Green;
                        datasname = Console.ReadLine();
                        Console.ResetColor();
                        Console.Write($"기존 국어점수: {array[fixinput - 1, 2]} >> ");
                        Console.ForegroundColor = ConsoleColor.Green;
                        datalanguage = Console.ReadLine();
                        Console.ResetColor();
                        Console.Write($"기존 수학점수: {array[fixinput - 1, 3]} >> ");
                        Console.ForegroundColor = ConsoleColor.Green;
                        datamath = Console.ReadLine();
                        Console.ResetColor();
                        Console.Write($"기존 영어점수: {array[fixinput - 1, 4]} >> ");
                        Console.ForegroundColor = ConsoleColor.Green;
                        dataenglish = Console.ReadLine();
                        Console.ResetColor();
                        array[fixinput - 11= datasname;
                        array[fixinput - 12= datalanguage;
                        array[fixinput - 13= datamath;
                        array[fixinput - 14= dataenglish;
                        language = Convert.ToInt32(array[fixinput - 12]);
                        math = Convert.ToInt32(array[fixinput - 13]);
                        english = Convert.ToInt32(array[fixinput - 14]);
                        mean = (language + math + english) / 3;
                        strmean = Convert.ToString(mean);
                        array[fixinput - 15= strmean;
                        float sumlanguage = 0.00f;
                        float summath = 0.00f;
                        float sumenglish = 0.00f;
                        float sumtotal = 0.00f;
                        for (int i2 = 0; i2 < keynum; i2++)
                        {
                            sumlanguage = sumlanguage + Convert.ToInt32(array[i2, 2]);
                            summath = summath + Convert.ToInt32(array[i2, 3]);
                            sumenglish = sumenglish + Convert.ToInt32(array[i2, 4]);
                            sumtotal = sumtotal + Convert.ToInt32(array[i2, 5]);
                        }
                        avglanguage = sumlanguage / keynum;
                        avgmath = summath / keynum;
                        avgenglish = sumenglish / keynum;
                        avgtotal = sumtotal / keynum;
                    }
                    else if (fixinput == 0)
                    {
                        goto Restart1;
                    }
                    Console.Clear();
 
                }//수정
                else if (finput == "4")//삭제
                {
                    Console.Clear();
                    Console.Write("Total Student: ");
                    Console.ForegroundColor = ConsoleColor.Blue;
                    Console.WriteLine(keynum);
                    Console.ResetColor();
                    Console.WriteLine();
                    Console.WriteLine("+----+----------------+------+------+------+------+");
                    Console.WriteLine("|번호|     학생명     | 국어 | 수학 | 영어 | 평균 |");
                    Console.WriteLine("+----+----------------+------+------+------+------+");
                    for (int i = 0; i < keynum; i++)
                    {
                        int namebytelen = Encoding.Default.GetBytes(array[i, 1]).Length;
                        int padlen = 8 - (namebytelen / 2);
                        Console.Write("|");
                        Console.Write(formatString, (i + 1));
                        Console.Write("|");
                        if (namebytelen % 2 != 0)
                        {
                            Console.Write("{0}""".PadLeft(padlen) + array[i, 1+ "".PadRight(padlen - 1+ "|");
                        }
                        else
                        {
                            Console.Write("{0}""".PadLeft(padlen) + array[i, 1+ "".PadRight(padlen) + "|");
                        }
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write(String.Format("{0,6}", array[i, 2])); //국어
                        Console.ResetColor();
                        Console.Write("|");
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write(String.Format("{0,6}", array[i, 3]));//수학
                        Console.ResetColor();
                        Console.Write("|");
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write(String.Format("{0,6}", array[i, 4]));//영어
                        Console.ResetColor();
                        Console.Write("|");
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Write(String.Format("{0,6}", array[i, 5])); //평균
                        Console.ResetColor();
                        Console.WriteLine("|");
 
                    }
                    Console.WriteLine("+----+----------------+------+------+------+------+");
                    Console.WriteLine(String.Format("|    | 전체 학생 평균 |{0,6}|{1,6}|{2,6}|{3,6}|", avglanguage.ToString("F2"), avgmath.ToString("F2"), avgenglish.ToString("F2"), avgtotal.ToString("F2"))); //전체학생평균
                    Console.WriteLine("+----+----------------+------+------+------+------+");
                    if (keynum == 0)
                    {
                        Console.WriteLine("저장된 데이터 정보가 없습니다.");
                        
                    }
                    else
                    {
                        Console.Write($"삭제할 데이터 번호를 입력하세요({array[0, 0]}~{keynum}) [0 : Exit]: ");
                        int sinput = Convert.ToInt32(Console.ReadLine());
                        if (sinput <= keynum && sinput != 0)
                        {
                            for (int i5 = sinput; i5 < keynum + 1; i5++)
                            {
                                array[i5 - 10= Convert.ToString(i5);
                                array[i5 - 11= array[i5, 1];
                                array[i5 - 12= array[i5, 2];
                                array[i5 - 13= array[i5, 3];
                                array[i5 - 14= array[i5, 4];
                                array[i5 - 15= array[i5, 5];
                            }
                            keynum--;
                            float sumlanguage = 0.00f;
                            float summath = 0.00f;
                            float sumenglish = 0.00f;
                            float sumtotal = 0.00f;
                            if (keynum!=0)
                            {                            
                            for (int i2 = 0; i2 < keynum; i2++)
                            {
                                sumlanguage = sumlanguage + Convert.ToInt32(array[i2, 2]);
                                summath = summath + Convert.ToInt32(array[i2, 3]);
                                sumenglish = sumenglish + Convert.ToInt32(array[i2, 4]);
                                sumtotal = sumtotal + Convert.ToInt32(array[i2, 5]);
                            }
                            avglanguage = sumlanguage / keynum;
                            avgmath = summath / keynum;
                            avgenglish = sumenglish / keynum;
                            avgtotal = sumtotal / keynum;
                            }
                            else if (keynum == 0)
                            {
                                avglanguage = 0.00f;
                                avgmath = 0.00f;
                                avgenglish = 0.00f;
                                avgtotal = 0.00f;
                            }
                            Console.Clear();
 
                        }
                        else if (sinput == 0)
                        {
                            goto Restart1;
                        }
 
                    }
 
                }//삭제
                else if (finput == "0")//종료
                {
                    break;
                }
                else
                {
                    Console.WriteLine("없는 메뉴입니다.");
                }
 
            }
 
        }
 
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

아직 함수를 배우지 않아서 표를 출력하는 메소드가 3번씩이나 반복되었다. 

함수를 배운다면 코드가 훨씬 짧아질것이다.

또한 데이터를 삭제할때 다음 행의 값을 한칸씩 밀려서 덮어씌우는 방식으로 해서 표에서는 보이진않지만 실질적으로 배열 안에는 마지막 행의 데이터가 그대로남아있다. 배열을 좀더 공부해서 데이터를 완전히 삭제할 수 있으면 좋겠다.

'C# > Study' 카테고리의 다른 글

박싱과 언박싱  (0) 2019.10.31
배열 내 요소중 최대값 구하기  (0) 2019.10.15
1차원 배열  (0) 2019.09.24
09.23 Row와 Column 설정하기  (0) 2019.09.23
문자열 표현방식  (0) 2019.09.19
:

String.Format을 이용하지않은 중앙정렬

C#/Problems 2019. 9. 27. 11:45

Console.WriteLine(String.Format("{0,42}", "길동"));

String.Format 메소드를 사용하면 입력하고자 하는 문자열("길동")의 길이를 .Length 를 이용해 자동 인식한다.

자동 인식한 문자열의 길이에서 총길이 (42)에서 문자열 길이만큼을 뺀 나머지를 공백으로 오른쪽을 채워넣는다.

여기서 문제는 자동인식할때 문자열이 한글일때도 한글자당 길이를 1로 인식한다.

자동으로 문자열 길이를 인식하므로 Encoding. Default. GetBytes(문자열) 이 문을 사용해 따로 문자열의 길이를 지정해줄 수가없다. 

따라서 String.Format을 사용하지 않고 임의적으로 공간을 앞에 주는데 그 공간의 갯수는 총 길이 - 문자열바이트값 이다.

앞에 두는 빈공간을 뒤에도 똑같이 두게되면 문자는 중앙으로 오게된다.

총길이가 16칸인 칸에 앞뒤로 같은 빈공간을 두면서 문자를 정렬을 하기위한 식:

int bytelen = Encoding.Default.GetBytes(name[i]).Length;

int padlen = 8 - (bytelen / 2);

하지만 여기서 input 값이 영문일 경우, input의 byte길이 나누기 2를 하는 과정에서 소수가 발생할 수 가있다.

예를 들어 문자열이 영문 "a' 한글자 일때 2를 나누면 0.5가 된다.

여기서 padlen 의 타입은 int이기 때문에 0.5를 1로 반환한다.

1로 반환하게되면 반올림된 0.5의 값이 앞뒤로 두개가 되어 총 길이가 한칸이 늘어나는 현상이 생긴다

bytelen % 2 != 0 일때의 상황을 따로 만들어 뒤에 오는 빈공간이 한칸 줄게 만들어줬다.

if (bytelen % 2 != 0) 
                {
                    Console.WriteLine("{0}", "".PadLeft(padlen) + name[i] + "".PadRight(padlen-1) + "1");
                }
                else 
                {
                    Console.WriteLine("{0}", "".PadLeft(padlen) + name[i] + "".PadRight(padlen) + "1");
                }

:

한글과 영문,숫자의 바이트 인식

C#/Problems 2019. 9. 27. 10:23

format.string 을 이용해 정렬을 하려고 할때 시스템은 한글 한글자와 영문 한글자의 길이를 똑같이 1로 인식해서 정렬할때 문제가 생긴다.

이 문제를 해결하기 위해 새로운 변수를 만들어 그 변수의 값에 input 문자열의 바이트 값을 구하여 padingleft 의 값을 조절해주면 된다.

코드:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _09._27_step1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] name = new string[] { "홍길동" , "길동""abc""ab"};
            
            for (int i = 0; i < name.Length; i++)
            {
                int padlen = 10 - Encoding.Default.GetBytes(name[i]).Length;
                Console.WriteLine("{0}","".PadLeft(padlen)+ name[i]);
            }
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

출력:

 

 

:

더하기 사이클

C#/Algorithm 2019. 9. 27. 09:34

문제

0보다 크거나 같고, 99보다 작거나 같은 정수가 주어질 때 다음과 같은 연산을 할 수 있다. 먼저 주어진 수가 10보다 작다면 앞에 0을 붙여 두 자리 수로 만들고, 각 자리의 숫자를 더한다. 그 다음, 주어진 수의 가장 오른쪽 자리 수와 앞에서 구한 합의 가장 오른쪽 자리 수를 이어 붙이면 새로운 수를 만들 수 있다. 다음 예를 보자.

26부터 시작한다. 2+6 = 8이다. 새로운 수는 68이다. 6+8 = 14이다. 새로운 수는 84이다. 8+4 = 12이다. 새로운 수는 42이다. 4+2 = 6이다. 새로운 수는 26이다.

위의 예는 4번만에 원래 수로 돌아올 수 있다. 따라서 26의 사이클의 길이는 4이다.

N이 주어졌을 때, N의 사이클의 길이를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 N이 주어진다. N은 0보다 크거나 같고, 99보다 작거나 같은 정수이다.

출력

첫째 줄에 N의 사이클 길이를 출력한다.

예제 입력 1

26

예제 출력 1

4

예제 입력 2

55

예제 출력 2

3

예제 입력 3

1

예제 출력 3

60

코드

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _1110
{
    class Program
    {
        static void Main(string[] args)
        {
            string N = Console.ReadLine();
            string fN = N;
            int count = 0;
            if (N.Length < 3 && N.Length > 1)
            {
                while (true)
                {
                    string stra = Convert.ToString(N[0]);
                    int a = Convert.ToInt32(stra);
                    string strb = Convert.ToString(N[1]);
                    int b = Convert.ToInt32(strb);
                    if (a + b < 10)
                    {
                        N = b + Convert.ToString(a + b);
                        count++;
                    }
                    else if (a + b >= 10)
                    {
                        string sum = Convert.ToString(a + b);
                        N = Convert.ToString(b) + sum[1];
                        count++;
                    }
                    if (N == fN)
                    {
                        break;
                    }
                }
                Console.WriteLine(count);
            }
            else if (N.Length == 1)
            {
                N = "0" + N;
                while (true)
                {                    
                    string stra = Convert.ToString(N[0]);
                    int a = Convert.ToInt32(stra);
                    string strb = Convert.ToString(N[1]);
                    int b = Convert.ToInt32(strb);
                    if (a + b < 10)
                    {
                        N = b + Convert.ToString(a + b);
                        count++;
                    }
                    else if (a + b >= 10)
                    {
                        string sum = Convert.ToString(a + b);
                        N = Convert.ToString(b) + sum[1];
                        count++;
                    }
                    if (N == "0" + fN)
                    {
                        break;
                    }
                }
                Console.WriteLine(count);
            }
        }
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

나같은 경우에는 input 값(string)을 int 값으로 한 글자씩 분리 변환하는 과정에서

저장된 input값을 배열을 이용해 각각 한글자씩 char 형태로 분리 --> char 형태의 각각의 글자를 string 형태로 변환 --> 다시 int 값으로 변환해서 식의 값을 구했다. 

함수 식 자체는 어렵지는 않지만 유저의 input값을 숫자형태, 문자열 형태로 자주 바꿔야했다. 

char 형태의 문자열 각각의 문자를 int 로 바꾸는 과정에는 중간에 string 형태로 변환하고나서 int로 변환 해야한다는 사실을 간과해 시간이 조금 걸렸던 문제이다.

(char '1' --> string '1' --> int 1)

하지만 나중에 조사해 본 결과 input 자체를 int로 받고 input / 10 과 input % 10 을 통해 1의 자리 숫자와 10의 자리 숫자를 분리 해서 식을 세우면 코드가 훨씬 짧아진다는 사실을 알았다. 이 방법의 장점은 input이 10보다 작을때 앞에 0을 붙여주는 과정을 생략할 수 있다는 것이다.

참조: https://www.acmicpc.net/problem/1110

'C# > Algorithm' 카테고리의 다른 글

2920 음계  (0) 2019.10.10
10.07 str.Replace( x, y ) 활용  (0) 2019.10.07
클래식 다이얼  (0) 2019.09.26
돌 게임  (0) 2019.09.26
설탕 배달  (0) 2019.09.25
:

switch 문

C#/실습 2019. 9. 26. 13:14
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _09._26_step1
{
    class Program
    {
        static void Main(string[] args)
        {
            string itemname = "장검";
            /*switch (itemname)
            {
                case "장검":
                    Console.WriteLine("장검을 선택했습니다.");
                    break;
                case "단검":
                    Console.WriteLine("단검을 서낵했습니다.");
                    break;
                default:
                    Console.WriteLine("{0}을 선택할 수 없습니다.", itemname);
                    break;
            }
            */
            /*if (itemname == "장검")
            {
                Console.WriteLine("장검을 선택했습니다");
            }
            else if (itemname == "단검")
            {
                Console.WriteLine("단검을 선택했습니다");
            }
            else
            {
                Console.WriteLine("{0}을 선택했습니다.", itemname);
            }*/
            string input = Console.ReadLine();
            switch(input)
            {
                case "1":
                    Console.WriteLine("안녕하세요");
                    break;
                case "2":
                    Console.WriteLine("반갑습니다");
                    break;
                default:
                    Console.WriteLine("감사합니다.");
                    break;
            }
            Console.WriteLine("성적을 입력하세요");
            string score = Console.ReadLine();
            switch (score)
            {
                case "a":
                    Console.WriteLine("90~100");
                    break;
                case "b":
                    Console.WriteLine("80~89");
                    break;
                case "c":
                    Console.WriteLine("70~79");
                    break;
                case "d":
                    Console.WriteLine("60~69");
                    break;
                case "f":
                    Console.WriteLine(0);
                    break;
            }
            Console.WriteLine("달 입력");
            string month = Console.ReadLine();
            switch (month)
            {
                case "1":
                case "3":
                case "5":
                case "7":
                case "8":
                case "10":
                case "12":
                    Console.WriteLine(31);
                    break;
                case "4":
                case "6":
                case "9":
                case "11":
                case "2":
                    Console.WriteLine(30);
                    break;
                default:
                    Console.WriteLine(-1);
                    break;
            }
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

'C# > 실습' 카테고리의 다른 글

10.01 여러 class를 이용해 햄버거 세트 만들기  (0) 2019.10.01
워크래프트 캐릭생성하기  (0) 2019.09.27
09.24 최대공약수 구하기  (0) 2019.09.24
09.23 상점 구매하기 및 판매하기  (0) 2019.09.23
09.20 줄넘기  (0) 2019.09.20
: