C#/Head First C# Practice (6)
슬라피 조의 샌드위치 하우스, 메뉴 랜덤하게 만들기(배열 연습)

[설명]

고기, 빵, 소스를 랜덤하게 선택하여 메뉴를 만들어 봄으로써 배열을 연습

 

[실행화면]

 

[소스코드]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SloppyJoeMenu
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            MenuMaker menu = new MenuMaker() { Randomizer = new Random() };
            this.label1.Text = menu.GetMenuItem();
            this.label2.Text = menu.GetMenuItem();
            this.label3.Text = menu.GetMenuItem();
            this.label4.Text = menu.GetMenuItem();
            this.label5.Text = menu.GetMenuItem();
            this.label6.Text = menu.GetMenuItem();
        }

        public class MenuMaker
        {
            public Random Randomizer;

            string[] Meats = { "Roast beef", "Salami", "Turkey", "Ham", "Pastrami" };
            string[] Condiments = { "yellow mustard", "brown mustard", "honey mustard", "mayo", "relish", "french dressing" };
            string[] Breads = { "rye", "white", "wheat", "pumpernickel", "italian bread", "a roll" };

            public string GetMenuItem()
            {
                string randomMeat = Meats[Randomizer.Next(Meats.Length)];
                string randomCondiment = Condiments[Randomizer.Next(Condiments.Length)];
                string randomBreads = Breads[Randomizer.Next(Breads.Length)];
                return randomMeat + " with " + randomCondiment + " on " + randomBreads;
            }
        }
    }
}

  Comments,     Trackbacks
인스턴스의 속성을 맞바꾸기

[설명]

코끼리 인스턴스를 두 개 만든 다음 어떤 인스턴스도 가비지 컬렉션이 되지 않으면서도 두 인스턴스의 속성을 맞바꿀 수 있게 만들어 보자.
그냥 Iloyd=lucinda라고 하면 더 이상 어떤 참조변수도 Iloyd를 가리키지 않는 상태가 되어 그 객체는 사라지므로, temp라는 이름으로 잠시 그 객체를 객체를 챙겨둘 참조변수를 만들어서 Lucinda가 그 객체를 참조할 때까지 지켜줘야 한다.

 

[실행화면]

 

 

[소스코드]

  Comments,     Trackbacks
Mileage Calculator

[설명]

이동거리를 계산해 환급액을 알려주는 프로그램.
환급율은 0.39 (39%).


[실행화면]


[소스코드]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MileageCalc
{
    public partial class Form1 : Form
    {
        int startingMileage, endingMileage;
        double milesTraveled, amountOwed, reimburseRate = 0.39;

        private void btn_calcMiles_Click(object sender, EventArgs e)
        {
            MessageBox.Show(milesTraveled + " miles", "Miles Traveled");
        }

        private void btn_Calc_Click(object sender, EventArgs e)
        {
            startingMileage = (int)numericStart.Value;
            endingMileage = (int)numericEnd.Value;
            if (endingMileage > startingMileage)
            {
                milesTraveled = endingMileage - startingMileage;
                amountOwed = milesTraveled * reimburseRate;
                lbl_result.Text = "$" + amountOwed.ToString();
            } else
            {
                MessageBox.Show("출발 시 주행거리는 도착 시 주행거리보다 작아야 합니다!");
            }
        }

        public Form1()
        {
            InitializeComponent();
        }
    }
}



  Comments,     Trackbacks
메서드를 만들 때 정적(static) 키워드를 사용하는 이유

[관련 Page : 159]

정적(static) 키워드로 선언한 메서드는 객체 인스턴스(instance)를 생성하지 않고도 호출이 가능하다.
정적 메서드가 아닌 메서드는 객체 인스턴스를 생성(new 인스턴스 이름)하면 힙(heap)이라는 메모리 공간 안에 객체가 생성되므로, 인스턴스를 생성할 때 마다 별도의 객체가 생성이 된다.
정적(static) 키워드를 사용하는 이유는, 값을 공유하기 위한 용도로 사용하기 위함이다. (참조페이지 : https://wikidocs.net/228)


[연습코드]

* static 메서드의 경우는 바로 호출이 가능하지만, non-static 메서드의 경우는 인스턴스를 생성해 주어야만 호출이 가능한 것을 알 수 있었다.

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

namespace StaticTest
{
    class Program
    {
        static void Main(string[] args)
        {
            StatTest.StatPrn();
            StatTest nonTest = new StatTest();
            nonTest.Prn();
            // StatTest.Prn(); 빨간 밑줄!
        }
    }

    class StatTest
    {
        public static void StatPrn()
        {
            Console.Out.Write("Static에서 작동하는 Method\n");
        }

        public void Prn()
        {
            Console.Out.Write("non-Static에서 작동하는 Method\n");
        }
    }
}


  Comments,     Trackbacks
ExchangeMoney, 돈 송수금 하기

[설명]

Bob과 Joe의 돈을 은행을 통해 송금하자.
송금할 때 마다 수수료가 1달러씩 은행에 지불됨.
계속 송금하다 보면 결국 은행만 수수료로 돈을 벌고 Bob과 Joe는 거지가 됨.
Head First에 있는 예제와는 코드가 다소 다름.
어딘가 헛점이 많고 더 단축할 수 있는 코드이나 수정하기엔 할 일이 많다~

 

[실행화면] 

 

[소스코드]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ExMoney
{

    public partial class Form1 : Form
    {

        int bank = 0;
        int interest = 1;
        Guy bob = new Guy();
        Guy joe = new Guy();

        public Form1()
        {
            bob.cash = 100;
            joe.cash = 100;
            InitializeComponent();
            UpdateForm(); // InitializeComponent() 보다 먼저 수행하면 레퍼런스 에러!

        }

        private void btn_1_Click(object sender, EventArgs e)
        {
            int temp = bob.GiveCash(5, interest);
            if (temp != 0) // GiveCash()에서 0이 리턴될 경우는 송금한 돈이 없는 것이므로, 0이 아닐 때 수행되어야 함!
            {
                bank += temp;
                bank -= joe.ReceiveCash(temp - interest);
            }
            UpdateForm(); // Form 내용 갱신
        }

        private void btn_2_Click(object sender, EventArgs e)
        {
            int temp = joe.GiveCash(10, interest);
            if (temp != 0) // GiveCash()에서 0이 리턴될 경우는 송금한 돈이 없는 것이므로, 0이 아닐 때 수행되어야 함!
            {
                bank += temp;
                bank -= bob.ReceiveCash(temp - interest);
            }
            UpdateForm(); // Form 내용 갱신
        }
        
        public void UpdateForm()
        {
            bobMoney.Text = "Bob은 " + bob.cash + " 달러를 가지고 있습니다.";
            joeMoney.Text = "Joe는 " + joe.cash + " 달러를 가지고 있습니다.";
            bankMoney.Text = "은행은 " + bank + " 달러를 가지고 있습니다.";
        }
    }

    public class Guy
    {
        public string Name;
        public int cash;

        public int GiveCash(int amount, int interest)
        {
            if(cash >= amount+interest)
            {
                cash -= amount + interest;
                return amount + interest;
            }
            else
            {
                MessageBox.Show("송금할 돈이 부족합니다!");
                return 0;
            }

        }

        public int ReceiveCash(int amount)
        {
            cash += amount;
            return amount;
        }

    }
}

  Comments,     Trackbacks
Getting Start! 연습을 시작하며...

 


Head First C#

저자
앤드류 스텔만, 제니퍼 그린 지음
출판사
한빛미디어 | 2011-10-10 출간
카테고리
컴퓨터/IT
책소개
만화처럼 쉽고 빠르게 배우는 C# 4.0 프로그래밍, 닷넷 프레...
가격비교

 

 

C#은 JAVA와 문법이 비슷해서 익히는데 어려움이 없지만,
Head First에 나와 있는 예제 또는 연습문제를 차근히 따라해 보면서 객체지향에 대한 기초를 단단히 해 보고자 한다.

Head First는 어떤 내용을 참고하기에 다소 산만한 구성이어서 확실히 레퍼런스용 책으로는 적합하지 않다. 저자 또한 책에 그렇게 명시해 두었다.
그러니까, 코딩을 하다가, '그거 어떻게 사용했더라?' 하면서 책을 뒤적뒤적 거려야 할 때 이 책을 펼치게 되지는 않을 것이다.

이 책이 마음에 드는 점은,
아이러니하게도 그 특유의 산만함이다. 단점이자 장점인 것 같다.
어떠한 개념을 먼저 설명하는 것이 아니라 예제를 통해 일단 trial & error를 겪게 해 보고
그 과정에서 학습자들이 궁금해 할 법한 점들을 그 때 그 때 메모형식으로 풀어낸다는 점이다.
이러한 점이 뭔가 대학생이 되어 대학에 다시 간 것 같은 느낌이랄까...

예제 하나씩 끝내는 데만도 오랜 시간이 걸리지만 틈틈히 하여
이 책을 끝까지 끝내는 것을 목표로 할 것이다.

 

  Comments,     Trackbacks