[C#] For문 실습#3 달력출력
by #독개#Q) 2022 달력을 출력하시오
- 요일은 월,화,수,목,금,토,일
- 1월1일은 일요일로 가정한다
- 2월은 28일까지
For문에서 난이도가 있는 문제이다.
교수님의 풀이
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace exam8_8
{
internal class Obj
{
public void run()
{
Calendar calendar= new Calendar();
calendar.PrintCalender();
}
}
}
namespace exam8_8
{
internal class Calendar
{
//EndDate 필요 -> 31, 30, 28
//1월부터 12월
//31일로 끝나냐 30일로 끝나냐에 규칙이없으므로 모두 배열로 나열할수 밖에없다
private int[] Month31 = new int[] { 1, 3, 5, 7, 8, 10, 12 };
private int[] Month30 = new int[] { 4, 6, 9, 11 };
int CurrentDay;
public void PrintCalender()
{
for (int i = 1; i < 13; i++)
{
PrintHeader(i);
PrintMonth(i);
PrintFooter();
}
}
private void PrintHeader(int month)
{
Console.WriteLine($"{month}월");
Console.WriteLine("-----------------------------------");
//string.format은 공부해볼것 이런 노가다성 굉장히 싫어하나 아직 배운게 많이 없어서 어쩔 수 없다
Console.WriteLine(string.Format("{0,-4}{1,-4}{2,-4}{3,-4}{4,-4}{5,-4}{6,-4}", "일", "월", "화", "수", "목", "금", "토", "일"));
}
private void PrintFooter()
{
Console.WriteLine();
Console.WriteLine("-----------------------------------");
Console.WriteLine();
}
public void PrintMonth(int month)
{
int endDate;
if (Month31.Contains(month)) //Month31어레이야 month값 가지고있니?
endDate = 31;
else if (Month30.Contains(month))
endDate = 30;
else endDate = 28; //30,31일아니면 28일이니 2월이지
//month 월을 출력한다
PrintSpace(CurrentDay);
for (int i = 1; i <= endDate; i++)
PrintDate(i);
}
private void PrintSpace(int times)
{
for (int i = 0; i < times; i++)
Console.Write(string.Format("{0,-5}", " "));
}
public void PrintDate(int date)
{
Console.Write(string.Format("{0,-5}", date));
++CurrentDay;
if (CurrentDay == 7)
{
Console.WriteLine();
CurrentDay= 0;
}
}
}
}
결과

'🔥 프로그래밍 학습 > C#' 카테고리의 다른 글
| [C#] 스택과 힙 메모리 완전 정복 (0) | 2022.11.27 |
|---|---|
| [C#] 상속 (0) | 2022.11.24 |
| [C#] For문 실습#2 3의 배수 출력 (0) | 2022.11.24 |
| [C#] For문 실습#1 구구단 (0) | 2022.11.24 |
| [C#] 제어문 (0) | 2022.11.22 |
블로그의 정보
독한 개발자
#독개#