'프로그래밍/코드 정리'에 해당되는 글 6건

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

namespace Stream
{
    class Program
    {
        static void Main(string[] args)
        {
            /* Write */
            FileStream writeStream = new FileStream("test.txt", FileMode.Create);
            StreamWriter streamWriter = new StreamWriter(writeStream);

            streamWriter.WriteLine("IZONE");
            streamWriter.WriteLine("아이즈원");

            streamWriter.WriteLine("Jo Yuri");
            streamWriter.WriteLine("조유리");

            streamWriter.WriteLine("Choi Yena");
            streamWriter.WriteLine("최예나");

            streamWriter.Close();

            /* Read */
            FileStream readStream = File.Open("test.txt", FileMode.Open);
            StreamReader streamReader = new StreamReader(readStream);

            Console.WriteLine("streamReader.BaseStream.Length : " + streamReader.BaseStream.Length);
            
            while(false == streamReader.EndOfStream)
            {
                Console.WriteLine(streamReader.ReadLine());
            }

            streamReader.Close();
        }
    }
}

FileStream을 사용한 StreamWriter, StreamReader 사용법

 

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

namespace Stream
{
    class Program
    {
        static void Main(string[] args)
        {
            /* Write */
            StreamWriter streamWriter = new StreamWriter("StandAlone.txt");

            streamWriter.WriteLine("김민주");
            streamWriter.WriteLine("안유진");
            streamWriter.WriteLine("히토미");
            streamWriter.WriteLine("사쿠라");

            streamWriter.Close();

            /* Read */
            StreamReader streamReader = new StreamReader("StandAlone.txt"); ;

            while(false == streamReader.EndOfStream)
            {
                Console.WriteLine(streamReader.ReadLine());
            }

            streamReader.Close();
        }
    }
}

StreamWriter, StreamReader 단독 사용법

'프로그래밍 > 코드 정리' 카테고리의 다른 글

[C#] BitConverter 테스트  (0) 2021.04.02
[C#] 성적 정렬 프로그램  (0) 2021.03.29
[C#] 성적 입력 프로그램  (0) 2021.03.25
[C#] 우승할 달리기 선수 맞추기  (0) 2021.03.21
[C#] 성적 프로그램  (0) 2021.03.20
블로그 이미지

NIA1995

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

namespace BitConverter
{
    class Program
    {
        const string fileName = "BitConverter.txt";

        static void Main(string[] args)
        {
            long longValue = 1234567890123456789;
            int intValue = 100;
            string stringValue = "IZONE";

            char[] charArrayValue = stringValue.ToCharArray();

            Console.WriteLine("Default Data");
            Console.WriteLine("----------------------");
            Console.WriteLine(longValue);
            Console.WriteLine(intValue);
            Console.WriteLine(stringValue);
            Console.WriteLine();


            /* Write Start */
            Stream writeStream = new FileStream(fileName, FileMode.Create);
            
            /* Long Test */
            byte[] writeByBytes = BitConverter.GetBytes(longValue);

            Console.WriteLine("Byte Data");
            Console.WriteLine("----------------------");

            Console.Write("Byte : ");

            foreach (var item in writeByBytes)
            {
                /* 2진수 출력 0:X */
                Console.Write("{0:X2} ", item);
            }

            Console.WriteLine();

            writeStream.Write(writeByBytes, 0, writeByBytes.Length);

            /* Integer Test */
            writeByBytes = BitConverter.GetBytes(intValue);

            Console.Write("Byte : ");

            foreach (var item in writeByBytes)
            {
                Console.Write("{0:X2} ", item);
            }

            Console.WriteLine();

            writeStream.Write(writeByBytes, 0, writeByBytes.Length);

            Console.Write("Byte : ");

            /* CharArray Test */
            foreach (var item in charArrayValue)
            {
                byte[] writeByByte = BitConverter.GetBytes(item);

                writeStream.Write(writeByByte, 0, writeByByte.Length - 1);

                Console.Write("{0:X2} ", Convert.ToInt32(item));
            }

            Console.WriteLine("\n");
            writeStream.Close();
            /* Write End */


            /* Read Start */
            FileStream readStream = new FileStream(fileName, FileMode.Open);


            byte[] readBytes = new byte[sizeof(long)];

            readStream.Read(readBytes, 0, readBytes.Length);

            long readLongValue = BitConverter.ToInt64(readBytes, 0);


            readBytes = new byte[sizeof(int)];

            readStream.Read(readBytes, 0, readBytes.Length);

            int readIntValue = BitConverter.ToInt32(readBytes, 0);


            string readStringValue = "";

            readBytes = new byte[readStream.Length];

            readStream.Read(readBytes, 0, readBytes.Length);

            foreach (var item in readBytes)
            {
                readStringValue += (char)item;
            }

            Console.WriteLine("Result Data");
            Console.WriteLine("----------------------");

            Console.WriteLine(readLongValue);
            Console.WriteLine(readIntValue);
            Console.WriteLine(readStringValue);

            readStream.Close();
            /* Read End */
        }
    }
}

----------------------------------------------------
Default Data
----------------------
1234567890123456789
100
IZONE

Byte Data
----------------------
Byte : 15 81 E9 7D F4 10 22 11
Byte : 64 00 00 00
Byte : 49 5A 4F 4E 45

Result Data
----------------------
1234567890123456789
100
IZONE

'프로그래밍 > 코드 정리' 카테고리의 다른 글

[C#] StreamWriter, StreamReader  (0) 2021.04.02
[C#] 성적 정렬 프로그램  (0) 2021.03.29
[C#] 성적 입력 프로그램  (0) 2021.03.25
[C#] 우승할 달리기 선수 맞추기  (0) 2021.03.21
[C#] 성적 프로그램  (0) 2021.03.20
블로그 이미지

NIA1995

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

namespace @Sort
{
    class Program
    {
        class StudentData
        {
            private int id;
            private int kor;
            private int math;
            private int eng;
            private int total;

            public int ID
            {
                get { return id; }
            }

            public int Kor
            {
                get { return kor; }
            }

            public int Math
            {
                get { return math; }
            }

            public int Eng
            {
                get { return eng; }
            }

            public int Total
            {
                get { return total; }
            }

            public StudentData(int id, int kor, int math, int eng)
            {
                this.id = id;
                this.kor = kor;
                this.math = math;
                this.eng = eng;

                total = kor + math + eng;
            }
        }

        static void Main(string[] args)
        {
            List<StudentData> dataList = new List<StudentData>();

            bool isLoop = true;

            InitData(dataList, 20);

            do
            {
                Console.WriteLine("메뉴를 골라주세요 !");
                Console.Write("(1)id정렬 (2)성적 순 정렬 (3) 국어 점수 정렬 (4)특정 점수 이상 (5)특정 점수 이하 (0)나가기");
                string inputNum = Console.ReadLine();

                switch (inputNum)
                {
                    case "0":
                        Console.WriteLine("프로그램 종료");
                        isLoop = false;
                        break;

                    case "1":
                        SortDataByID(dataList);
                        break;

                    case "2":
                        SortDataByTotal(dataList);
                        break;

                    case "3":
                        SortDataByKor(dataList);
                        break;

                    case "4":
                        SortData(dataList, true);
                        break;

                    case "5":
                        SortData(dataList, false);
                        break;

                    default:
                        Console.Clear();
                        Console.WriteLine("다시 입력해 주세요!");
                        break;
                }

            } while (isLoop);
        }

            static void InitData(List<StudentData> dataList, int initCount)
        {
            Random rnd = new Random();

            for(int i = 0; i < initCount; ++i)
            {
                dataList.Add(new StudentData(i+1, rnd.Next(0, 101), rnd.Next(0, 101), rnd.Next(0, 101)));
            }
        }

        static void PrintData(List<StudentData> dataList)
        {
            Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", "ID", "KOR", "MATH", "ENG", "TOTAL");
            Console.WriteLine("---------------------------------------");

            for(int i = 0; i < dataList.Count(); ++i)
            {
                Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", dataList[i].ID, dataList[i].Kor, dataList[i].Math, dataList[i].Eng, dataList[i].Total);
            }
        }

        static void SortDataByID(List<StudentData> listData)
        {
            listData.Sort(delegate (StudentData a, StudentData b)
            {
                if (a.ID > b.ID)
                {
                    return 1;
                }
                else if (a.ID < b.ID)
                {
                    return -1;
                }
                else
                {
                    return 0;
                }
            });

            Console.WriteLine("아이디 정렬 !");
            PrintData(listData);
        }

        static void SortDataByTotal(List<StudentData> listData)
        {
            /* var data = 와 같다. */
            IOrderedEnumerable<StudentData> data = 
                from item in listData
                orderby item.Total descending
                select item;

            List<StudentData> sortedData = data.ToList();

            Console.WriteLine("총점 정렬 !");
            PrintData(sortedData);
        }

        static void SortDataByKor(List<StudentData> listData)
        {
            listData.Sort((StudentData a, StudentData b) =>
            {
                return b.Kor - a.Kor;
            });

            Console.WriteLine("국어 기준 정렬 !");
            PrintData(listData);
        }

        static void SortData(List<StudentData> listData, bool isASC)
        {
            Console.Write("기준 점수 입력 : ");
            string targetScore = Console.ReadLine();

            int num = 0;

            try
            {
                num = int.Parse(targetScore);
            }
            catch(FormatException e)
            {
                Console.Clear();
                Console.WriteLine("올바르지 않은 문자 형식입니다. 숫자만 입력 가능 합니다!");
            }
            finally
            {
                if(num < 0)
                {
                    Console.Clear();
                    Console.WriteLine("잘못된 입력 범위 입니다. -1보다 큰 수를 입력하세요 !");
                }
                
                if(num > 300)
                {
                    Console.Clear();
                    Console.WriteLine("잘못된 입력 범위 입니다. 301보다 작은 수를 입력하세요 !");
                }
            }

            if(num > -1 && num < 301)
            {
                if(isASC)
                {
                    var datas =
                        from item in listData
                        where item.Total >= num
                        select item;

                    List<StudentData> sortedData = datas.ToList();

                    PrintData(sortedData);
                }
                else
                {
                    var datas =
                            from item in listData
                            where item.Total <= num
                            select item;

                    List<StudentData> sortedData = datas.ToList();

                    PrintData(sortedData);
                }
            }         
        }
    }
}

'프로그래밍 > 코드 정리' 카테고리의 다른 글

[C#] StreamWriter, StreamReader  (0) 2021.04.02
[C#] BitConverter 테스트  (0) 2021.04.02
[C#] 성적 입력 프로그램  (0) 2021.03.25
[C#] 우승할 달리기 선수 맞추기  (0) 2021.03.21
[C#] 성적 프로그램  (0) 2021.03.20
블로그 이미지

NIA1995

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

namespace Test
{
    struct ScoreData
    {
        int id;

        public int ID
        {
            get => id;
            set
            {
                id = value;
            }
        }

        int kor;
        int math;
        int eng;

        public ScoreData(int Id, int Kor = 0, int Math = 0, int Eng = 0)
        {
            id = Id;
            kor = Kor;
            math = Math;
            eng = Eng;
        }

        public void Print()
        {
            Console.WriteLine("ID : {0}, 국어 : {1}, 수학 : {2}, 영어 : {3} 입니다.", id, kor, math, eng);
        }
    }

    class ScoreSystem
    {
        public List<ScoreData> dataList = new List<ScoreData>();

        public ScoreSystem()
        {
            for(int i = 0; i < 3; ++i)
            {
                Console.WriteLine("{0} 번 째 데이터를 입력 받겠습니다. 먼저, ID, 국어, 수학, 영어 성적을 차례 대로 입력해 주세요.", i + 1);

                int tempID   = int.Parse(Console.ReadLine());
                int tempKor  = int.Parse(Console.ReadLine());
                int tempMath = int.Parse(Console.ReadLine());
                int tempEng  = int.Parse(Console.ReadLine());

                dataList.Add(new ScoreData(tempID, tempKor, tempMath, tempEng));
            }
        }

        public void PrintData(int Id)
        {
            for(int i = 0; i < dataList.Count(); ++i)
            {
                if(Id == dataList[i].ID)
                {
                    dataList[i].Print();
                }
            }
        }
    }



    class Program
    {
        static void Main(string[] args)
        {
            ScoreSystem system = new ScoreSystem();

            while(true)
            {
                Console.WriteLine("보고 싶은 학생의 ID를 입력하세요. 단, 0은 프로그램 종료");

                int inputData = int.Parse(Console.ReadLine());

                if(inputData == 0)
                {
                    break;
                }
                else
                {
                    system.PrintData(inputData);
                }
            }
        }
    }
}

'프로그래밍 > 코드 정리' 카테고리의 다른 글

[C#] StreamWriter, StreamReader  (0) 2021.04.02
[C#] BitConverter 테스트  (0) 2021.04.02
[C#] 성적 정렬 프로그램  (0) 2021.03.29
[C#] 우승할 달리기 선수 맞추기  (0) 2021.03.21
[C#] 성적 프로그램  (0) 2021.03.20
블로그 이미지

NIA1995

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

namespace Test
{
    class Program
    {
        static int choosedPlayer;
        static int arrivalPlayer;

        const int MAP_X = 7;
        const int MAP_Y = 22;

        static int[,] initMapData =

            {
              /* 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 */
                {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
                {3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0},
                {4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0},
                {5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0},
                {6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0},
                {7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0},
                {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
            };

        static int[] InitarrCharacterIndex = { 0, 0, 0, 0, 0 };

        static int ChoicePlayer()
        {
            Console.Write("원하는 달리기 선수를 선택하세요 ! (1~5) : ");
            int targetPlayer = int.Parse(Console.ReadLine());

            if(targetPlayer > 5 || targetPlayer < 1)
            {
                Console.WriteLine("1번 부터 5번 선수 중에 선택하세요 ! ");
                return ChoicePlayer();
            }

            return targetPlayer;
        }

        static void ClearScreen()
        {            
            Thread.Sleep(300);
            Console.Clear();
        }

        static void RunPlayer(int[,] mapData, int[] playerData)
        {
            for(int i = 1; i < MAP_X - 1; ++i)
            {
                SwapTile(mapData, i, playerData[i-1]++);
            }
        }

        static void RandomRunPlayer(int[,] mapData, int[] playerData)
        {
            Random rnd = new Random();

            int boosterPlayer = rnd.Next(1, 6);

            SwapTile(mapData, boosterPlayer, playerData[boosterPlayer-1]++);
        }

        static void SwapTile(int [,] map, int x, int y)
        {
            int tempTile = map[x, y];
            map[x, y] = 0;
            map[x, y + 1] = tempTile;
        }

        static void DrawMap(int[,] mapData, char[] tileData)
        {
            for (int i = 0; i < MAP_X; ++i)
            {
                for (int j = 0; j < MAP_Y; ++j)
                {
                    int maptile = mapData[i, j];

                    Console.Write(tileData[maptile]);

                    if (j == MAP_Y - 1)
                    {
                        Console.WriteLine();
                    }
                }
            }
        }

        static bool IsArrival(int[] playerData)
        {
            for(int i = 0; i < playerData.Length; ++i)
            {
                if(playerData[i] >= 20)
                {
                    arrivalPlayer = i;
                    return true;
                }
            }

            return false;
        }

        static void Main()
        {
            /*               0    1    2    3    4    5    6    7     타일 데이터 */
            char[] tile = { ' ', '-', '|', '1', '2', '3', '4', '5' };

            /* 실제 맵 데이터 */
            int[,] mapData = (int[,])initMapData.Clone();

            /* 달리기 선수의 위치 */
            int[] arrCharacterIndex = (int[])InitarrCharacterIndex.Clone();

            while(true)
            {
                Console.WriteLine(" Runner Game ! ");

                choosedPlayer = ChoicePlayer();

                Console.WriteLine("잠시 후 게임을 시작합니다 !");

                while (true)
                {
                    if (IsArrival(arrCharacterIndex))
                    {
                        Console.WriteLine("{0} 번 째 선수가 먼저 도착했습니다 !", arrivalPlayer + 1);

                        if (choosedPlayer == arrivalPlayer + 1)
                        {
                            Console.WriteLine("선택한 플레이어가 우승했습니다 ! 축하합니다 !");
                        }
                        else
                        {
                            Console.WriteLine("아쉽게도 우승자를 맞히지 못했습니다.");
                        }

                        Thread.Sleep(2000);

                        break;
                    }

                    ClearScreen();

                    RunPlayer(mapData, arrCharacterIndex);

                    DrawMap(mapData, tile);

                    ClearScreen();

                    RandomRunPlayer(mapData, arrCharacterIndex);

                    DrawMap(mapData, tile);                    
                }

                ClearScreen();

                Console.Write("다시 하시겠습니까? (YES -> 1 , 그 외 종료 : ");

                int reStart = int.Parse(Console.ReadLine());

                if (reStart == 1)
                {
                    mapData = initMapData;
                    arrCharacterIndex = InitarrCharacterIndex;
                }
                else
                {
                    break;
                }
            }
        }         
    }
}

'프로그래밍 > 코드 정리' 카테고리의 다른 글

[C#] StreamWriter, StreamReader  (0) 2021.04.02
[C#] BitConverter 테스트  (0) 2021.04.02
[C#] 성적 정렬 프로그램  (0) 2021.03.29
[C#] 성적 입력 프로그램  (0) 2021.03.25
[C#] 성적 프로그램  (0) 2021.03.20
블로그 이미지

NIA1995

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

namespace Test
{
    class Program
    {
        int[] arrweek = new int[7]{1,2,3,4,5,6,7};

        /* 성적 프로그램 시작 */
        static void Start()
        {
            Console.WriteLine("성적 프로그램 - Method");
        }

        /* 성적 입력 */
        static void Input(ref int kor, ref int mat, ref int eng)
        {
            Console.Write("국어 성적 입력 : ");
            kor = Int32.Parse(Console.ReadLine());

            Console.Write("수학 성적 입력 : ");
            mat = Int32.Parse(Console.ReadLine());

            Console.Write("영어 성적 입력 : ");
            eng = Int32.Parse(Console.ReadLine());
        }

        /* 입력한 성적의 합 */
        static int Total(int kor, int mat, int eng)
        {
            return kor + mat + eng;
        }

        /* 성적의 평균 */
        static void Average(int total, out float average)
        {
            average = (float)total / 3;
        }

        static void Main(string[] args)
        {
            int kor = 0;
            int eng = 0;
            int mat = 0;
            int total;
            float average;

            Start();
            Input(ref kor, ref eng, ref mat);
            total = Total(kor, mat, eng);
            Average(total, out average);

            Console.WriteLine("Total : {0} / Average : {1}", total, average);
        }
    }
}

 

'프로그래밍 > 코드 정리' 카테고리의 다른 글

[C#] StreamWriter, StreamReader  (0) 2021.04.02
[C#] BitConverter 테스트  (0) 2021.04.02
[C#] 성적 정렬 프로그램  (0) 2021.03.29
[C#] 성적 입력 프로그램  (0) 2021.03.25
[C#] 우승할 달리기 선수 맞추기  (0) 2021.03.21
블로그 이미지

NIA1995

,