C# カレンダー・するべきリスト

メソッドのみ

using System;

namespace SampleConsole
{
    public class Calendar
    {
        public static void Main(string[] args)
        {
            int year, month;

            // 年の入力
            Console.WriteLine("カレンダーを表示する年と月を入力してください。");
            Console.Write("年を入力してください: ");
            while (!int.TryParse(Console.ReadLine(), out year))
            {
                Console.WriteLine("有効な年を入力してください。");
                Console.Write("年を入力してください: ");
            }

            // 月の入力と変換
            Console.Write("月を入力してください: ");
            while (!int.TryParse(Console.ReadLine(), out month) || month < 1 || month > 12)
            {
                Console.WriteLine("有効な月を入力してください(1から12の間)。");
                Console.Write("月を入力してください: ");
            }

            // カレンダーを表示
            DisplayCalendar(year, month);
        }

        static void DisplayCalendar(int year, int month)
        {
            int incrementDay = 1;
            int emptyDay = 0;

            // 月初めの曜日の計算
            DateTime firstDayOfMonth = new DateTime(year, month, 1);
            int daysInMonth = DateTime.DaysInMonth(year, month);

            Console.WriteLine($"***** {year}{month}月 *****");
            Console.WriteLine(" 日 月 火 水 木 金 土");

            // カレンダーの出力
            for (int i = 0; i < 6; i++)
            {
                for (int j = 0; j < 7; j++)
                {
                    if (i == 0 && emptyDay != (int)firstDayOfMonth.DayOfWeek)
                    {
                        Console.Write("   "); // 空白日
                        emptyDay++;
                    }
                    else if (incrementDay > daysInMonth)
                    {
                        break; // 月の日数を超えたら終了
                    }
                    else
                    {
                        Console.Write($"{incrementDay,3}"); // 日付の出力
                        incrementDay++;
                    }
                }
                Console.WriteLine(); // 改行
            }
            Console.ReadLine();
        }



    }
}

無理くりクラスを使うと

using System;

namespace SampleConsole
{
    public class Calendar
    {
        public static void Main(string[] args)
        {
            int year, month;

            // 年の入力
            Console.WriteLine("カレンダーを表示する年と月を入力してください。");
            Console.Write("年を入力してください: ");
            while (!int.TryParse(Console.ReadLine(), out year))
            {
                Console.WriteLine("有効な年を入力してください。");
                Console.Write("年を入力してください: ");
            }

            // 月の入力と変換
            Console.Write("月を入力してください: ");
            while (!int.TryParse(Console.ReadLine(), out month) || month < 1 || month > 12)
            {
                Console.WriteLine("有効な月を入力してください(1から12の間)。");
                Console.Write("月を入力してください: ");
            }

            // カレンダーを表示
            DisplayCalendar(year, month);
        }

        static void DisplayCalendar(int year, int month)
        {
            int incrementDay = 1;
            int emptyDay = 0;

            // 月初めの曜日の計算
            DateTime firstDayOfMonth = new DateTime(year, month, 1);
            int daysInMonth = DateTime.DaysInMonth(year, month);

            Console.WriteLine($"***** {year}{month}月 *****");
            Console.WriteLine(" 日 月 火 水 木 金 土");

            // カレンダーの出力
            for (int i = 0; i < 6; i++)
            {
                for (int j = 0; j < 7; j++)
                {
                    if (i == 0 && emptyDay != (int)firstDayOfMonth.DayOfWeek)
                    {
                        Console.Write("   "); // 空白日
                        emptyDay++;
                    }
                    else if (incrementDay > daysInMonth)
                    {
                        break; // 月の日数を超えたら終了
                    }
                    else
                    {
                        Console.Write($"{incrementDay,3}"); // 日付の出力
                        incrementDay++;
                    }
                }
                Console.WriteLine(); // 改行
            }
            Console.ReadLine();
        }



    }
}

移動できる

using System;

namespace SampleConsole
{
    public class Calendar
    {
        public static void Main(string[] args)
        {
            var c = new DisplayCalendar();
            c.RunCalendar();
        }

        public class DisplayCalendar
        {
            private DateTime currentDay;
            private DateTime today;

            public DisplayCalendar()
            {
                today = DateTime.Today;
                currentDay = today;
            }

            public void RunCalendar()
            {
                bool continueRunning = true;
                while (continueRunning)
                {
                    Console.Clear();
                    DisplayCalendarMonth();
                    continueRunning = ProcessInput();
                }
            }

            private void DisplayCalendarMonth()
            {
                int daysInMonth = DateTime.DaysInMonth(currentDay.Year, currentDay.Month);
                DateTime firstDayOfMonth = new DateTime(currentDay.Year, currentDay.Month, 1);

                Console.WriteLine($"***** {currentDay.Year}{currentDay.Month}月 *****");
                Console.WriteLine(" 日 月 火 水 木 金 土");

                int dayOffset = (int)firstDayOfMonth.DayOfWeek;
                int dayPrinted = 1;

                for (int i = 0; i < 6; i++)
                {
                    for (int j = 0; j < 7; j++)
                    {
                        if (i == 0 && j < dayOffset)
                        {
                            Console.Write("   ");
                        }
                        else if (dayPrinted <= daysInMonth)
                        {
                            if (currentDay.Day == dayPrinted && currentDay.Month == today.Month && currentDay.Year == today.Year)
                                Console.Write($"[{dayPrinted,2}]");
                            else
                                Console.Write($"{dayPrinted,3}");

                            dayPrinted++;
                        }
                    }
                    Console.WriteLine();
                }
            }

            private bool ProcessInput()
            {
                ConsoleKeyInfo key = Console.ReadKey(true);

                switch (key.Key)
                {
                    case ConsoleKey.RightArrow:
                        MoveDay(1);
                        break;
                    case ConsoleKey.LeftArrow:
                        MoveDay(-1);
                        break;
                    case ConsoleKey.UpArrow:
                        MoveDay(-7);
                        break;
                    case ConsoleKey.DownArrow:
                        MoveDay(7);
                        break;
                    case ConsoleKey.Escape:
                        return false; // Stop running
                }

                return true; // Keep running
            }

            private void MoveDay(int days)
            {
                DateTime potentialNewDay = currentDay.AddDays(days);
                if (potentialNewDay.Month == currentDay.Month)
                {
                    currentDay = potentialNewDay;
                }
            }
        }
    }
}

Enter押下、メニュー画面表示

using System;

namespace SampleConsole
{
    public class Calendar
    {
        public static void Main(string[] args)
        {
            var c = new DisplayCalendar();
            c.RunCalendar();
        }

        public class DisplayCalendar
        {
            private DateTime currentDay;
            private DateTime today;

            public DisplayCalendar()
            {
                today = DateTime.Today;
                currentDay = today;
            }

            public void RunCalendar()
            {
                bool continueRunning = true;
                while (continueRunning)
                {
                    Console.Clear();
                    DisplayCalendarMonth();
                    continueRunning = ProcessInput();
                }
            }

            private void DisplayCalendarMonth()
            {
                int daysInMonth = DateTime.DaysInMonth(currentDay.Year, currentDay.Month);
                DateTime firstDayOfMonth = new DateTime(currentDay.Year, currentDay.Month, 1);

                Console.WriteLine($"***** {currentDay.Year}{currentDay.Month}月 *****");
                Console.WriteLine(" 日 月 火 水 木 金 土");

                int dayOffset = (int)firstDayOfMonth.DayOfWeek;
                int dayPrinted = 1;

                for (int i = 0; i < 6; i++)
                {
                    for (int j = 0; j < 7; j++)
                    {
                        if (i == 0 && j < dayOffset)
                        {
                            Console.Write("   ");
                        }
                        else if (dayPrinted <= daysInMonth)
                        {
                            if (currentDay.Day == dayPrinted)
                                Console.Write($"[{dayPrinted,2}]");
                            else
                                Console.Write($"{dayPrinted,3}");

                            dayPrinted++;
                        }
                    }
                    Console.WriteLine();
                }
            }

            private bool ProcessInput()
            {
                ConsoleKeyInfo key = Console.ReadKey(true);

                switch (key.Key)
                {
                    case ConsoleKey.RightArrow:
                        MoveDay(1);
                        break;
                    case ConsoleKey.LeftArrow:
                        MoveDay(-1);
                        break;
                    case ConsoleKey.UpArrow:
                        MoveDay(-7);
                        break;
                    case ConsoleKey.DownArrow:
                        MoveDay(7);
                        break;
                    case ConsoleKey.Enter:
                        ShowDayOptions(currentDay);
                        break;
                    case ConsoleKey.Escape:
                        return false; // Stop running
                }

                return true; // Keep running
            }

            private void MoveDay(int days)
            {
                DateTime potentialNewDay = currentDay.AddDays(days);
                if (potentialNewDay.Month == currentDay.Month)
                {
                    currentDay = potentialNewDay;
                }
            }

            private void ShowDayOptions(DateTime selectedDay)
            {
                int optionIndex = 0;
                string[] options = { "予定確認", "予定追加", "戻る" };
                bool inMenu = true;

                while (inMenu)
                {
                    Console.Clear();
                    Console.WriteLine($"{selectedDay.Year}{selectedDay.Month}{selectedDay.Day}日");

                    for (int i = 0; i < options.Length; i++)
                    {
                        if (i == optionIndex)
                            Console.WriteLine($"{options[i]} <");
                        else
                            Console.WriteLine(options[i]);
                    }

                    var keyOption = Console.ReadKey(true);
                    switch (keyOption.Key)
                    {
                        case ConsoleKey.UpArrow:
                            optionIndex = (optionIndex - 1 + options.Length) % options.Length;
                            break;
                        case ConsoleKey.DownArrow:
                            optionIndex = (optionIndex + 1) % options.Length;
                            break;
                        case ConsoleKey.Enter:
                            ExecuteOption(optionIndex, selectedDay);
                            break;
                        case ConsoleKey.Escape:
                            inMenu = false;
                            break;
                    }
                }
            }

            private void ExecuteOption(int optionIndex, DateTime selectedDay)
            {
                switch (optionIndex)
                {
                    case 0:
                        Console.WriteLine("予定を確認...");
                        // Implement schedule checking functionality
                        break;
                    case 1:
                        Console.WriteLine("予定を追加...");
                        // Implement adding a new schedule
                        break;
                    case 2:
                        // Just return to the calendar
                        break;
                }
                Console.WriteLine("Press any key to return...");
                Console.ReadKey();
            }
        }
    }
}

完成形

using System;
using System.Collections.Generic;
using System.Linq;


namespace SampleConsole
{
    public class Calendar
    {
        public static void Main(string[] args)
        {
            var c = new DisplayCalendar();
            c.RunCalendar();
        }
        



        public class DisplayCalendar
        {
            private DateTime currentDay;
            private DateTime today;
            private Dictionary<DateTime, List<string>> schedules;

            public DisplayCalendar()
            {
                today = DateTime.Today;
                currentDay = today;
                schedules = new Dictionary<DateTime, List<string>>();
                // 仮の予定データの追加
                schedules[currentDay] = new List<string> { "予定1", "予定2", "予定3" };
            }

            public void RunCalendar()
            {
                bool continueRunning = true;
                while (continueRunning)
                {
                    Console.Clear();
                    DisplayCalendarMonth();
                    continueRunning = ProcessInput();
                }
            }

            private void DisplayCalendarMonth()
            {
                int daysInMonth = DateTime.DaysInMonth(currentDay.Year, currentDay.Month);
                DateTime firstDayOfMonth = new DateTime(currentDay.Year, currentDay.Month, 1);

                Console.WriteLine($"***** {currentDay.Year}{currentDay.Month}月 *****");
                Console.WriteLine(" 日 月 火 水 木 金 土");

                int dayOffset = (int)firstDayOfMonth.DayOfWeek;
                int dayPrinted = 1;

                for (int i = 0; i < 6; i++)
                {
                    for (int j = 0; j < 7; j++)
                    {
                        if (i == 0 && j < dayOffset)
                        {
                            Console.Write("   ");
                        }
                        else if (dayPrinted <= daysInMonth)
                        {
                            if (currentDay.Day == dayPrinted)
                                Console.Write($"[{dayPrinted,2}]");
                            else
                                Console.Write($"{dayPrinted,3}");

                            dayPrinted++;
                        }
                    }
                    Console.WriteLine();
                }
            }

            private bool ProcessInput()
            {
                ConsoleKeyInfo key = Console.ReadKey(true);

                switch (key.Key)
                {
                    case ConsoleKey.RightArrow:
                        MoveDay(1);
                        break;
                    case ConsoleKey.LeftArrow:
                        MoveDay(-1);
                        break;
                    case ConsoleKey.UpArrow:
                        MoveDay(-7);
                        break;
                    case ConsoleKey.DownArrow:
                        MoveDay(7);
                        break;
                    case ConsoleKey.Enter:
                        ShowDayOptions(currentDay);
                        break;
                    case ConsoleKey.Escape:
                        return false; 
                }

                return true; 
            }

            private void MoveDay(int days)
            {
                DateTime potentialNewDay = currentDay.AddDays(days);
                currentDay = potentialNewDay;
            }

            private void ShowDayOptions(DateTime selectedDay)
            {
                int optionIndex = 0;
                string[] options = { "予定確認", "予定追加", "戻る" };
                bool inMenu = true;

                while (inMenu)
                {
                    Console.Clear();
                    Console.WriteLine($"{selectedDay.Year}{selectedDay.Month}{selectedDay.Day}日");

                    for (int i = 0; i < options.Length; i++)
                    {
                        if (i == optionIndex)
                            Console.WriteLine($"{options[i]} <");
                        else
                            Console.WriteLine(options[i]);
                    }

                    var keyOption = Console.ReadKey(true);
                    switch (keyOption.Key)
                    {
                        case ConsoleKey.UpArrow:
                            optionIndex = (optionIndex - 1 + options.Length) % options.Length;
                            break;
                        case ConsoleKey.DownArrow:
                            optionIndex = (optionIndex + 1) % options.Length;
                            break;
                        case ConsoleKey.Enter:
                            switch (optionIndex)
                            {
                                case 0: // 予定確認
                                    ShowSchedules(selectedDay);
                                    break;
                                case 1: // 予定追加
                                    AddNewSchedule(selectedDay);
                                    break;
                                case 2: // 戻る
                                    inMenu = false;
                                    break;
                            }
                            break;
                        case ConsoleKey.Escape:
                            inMenu = false;
                            break;
                    }
                }
            }

            private void AddNewSchedule(DateTime date)
            {
                Console.Clear();
                Console.WriteLine("新しい予定を入力してください:");
                string newPlan = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(newPlan))
                {
                    if (!schedules.ContainsKey(date))
                        schedules[date] = new List<string>();
                    schedules[date].Add(newPlan);
                    Console.WriteLine("予定が追加されました。");
                    Console.WriteLine("Enterキーを押して戻る...");
                    Console.ReadLine();
                }
            }


            private void ShowSchedules(DateTime date)
            {
                List<string> daySchedules = schedules.ContainsKey(date) ? schedules[date] : new List<string>();

                int scheduleIndex = 0;
                bool inSchedules = true;

                while (inSchedules)
                {
                    Console.Clear();
                    Console.WriteLine($"{date.Year}{date.Month}{date.Day}日の予定リスト");

                    for (int i = 0; i < daySchedules.Count; i++)
                    {
                        if (i == scheduleIndex)
                            Console.WriteLine($"{daySchedules[i]} <");
                        else
                            Console.WriteLine(daySchedules[i]);
                    }

                    if (scheduleIndex == daySchedules.Count)
                        Console.WriteLine("追加 <");
                    else
                        Console.WriteLine("追加");

                    if (scheduleIndex == daySchedules.Count + 1)
                        Console.WriteLine("戻る <");
                    else
                        Console.WriteLine("戻る");

                    var keySchedule = Console.ReadKey(true);
                    switch (keySchedule.Key)
                    {
                        case ConsoleKey.UpArrow:
                            scheduleIndex = (scheduleIndex - 1 + daySchedules.Count + 2) % (daySchedules.Count + 2);

                            break;
                        case ConsoleKey.DownArrow:
                            scheduleIndex = (scheduleIndex + 1) % (daySchedules.Count + 2);
                            break;
                        case ConsoleKey.Enter:
                            if (scheduleIndex < daySchedules.Count) // 既存の予定を選択
                            {
                                EditSchedule(daySchedules, scheduleIndex);
                            }
                            else if (scheduleIndex == daySchedules.Count) // '追加' オプション
                            {
                                AddSchedule(date, daySchedules);
                            }
                            else if (scheduleIndex == daySchedules.Count + 1) // '戻る' オプション
                            {
                                inSchedules = false;
                            }
                            break;
                        case ConsoleKey.Escape:
                            inSchedules = false;
                            break;
                    }
                }
            }

            private void EditSchedule(List<string> daySchedules, int index)
            {
                Console.Clear();
                Console.WriteLine("編集前の予定:");
                Console.WriteLine(daySchedules[index]);
                Console.WriteLine("\n新しい内容で予定を入力してください:");
                string newContent = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(newContent))
                {
                    daySchedules[index] = newContent;
                }
            }


            private void AddSchedule(DateTime date, List<string> daySchedules)
            {
                Console.Clear();
                Console.WriteLine("新しい予定を入力してください:");
                string newPlan = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(newPlan))
                {
                    daySchedules.Add(newPlan);
                    if (schedules.ContainsKey(date))
                        schedules[date] = daySchedules;
                    else
                        schedules.Add(date, daySchedules);
                }
            }


        }
    }
}

解説

クラス: DisplayCalendar

このクラスはアプリケーションの主要な機能を担っており、カレンダー表示、日付操作、予定の表示、追加、編集を行います。

プロパティとフィールド

  • private DateTime currentDay: 現在選択されている日付を追跡します。

  • private DateTime today: アプリケーションが起動された日の日付を保持します。

  • private Dictionary<DateTime, List<string>> schedules: 各日付に対する予定のリストを格納する辞書。キーはDateTimeで、値は予定のList<string>です。

コンストラクタ: DisplayCalendar()

コンストラクタでは、todaycurrentDay を現在の日付に設定し、schedules 辞書を初期化しています。さらに、今日の日付に仮の予定をいくつか追加しています。

メソッド: RunCalendar()

カレンダーのメインループを管理します。これにより、カレンダーの月表示が更新され、ユーザー入力が繰り返し処理されます。ProcessInput() メソッドの結果に基づいてループが継続または終了します。

メソッド: DisplayCalendarMonth()

指定された月のカレンダーをコンソールに表示します。月の日数と最初の日の曜日を計算し、適切な位置から日付を表示し始めます。現在の日 (currentDay) は角括弧で囲まれて強調表示されます。

メソッド: ProcessInput()

ユーザーからのキーボード入力を受け取り、対応するアクション(日付の移動、日付の選択)を実行します。矢印キーで日付を移動し、Enterキーで選択された日のオプションを表示します。

メソッド: MoveDay(int days)

指定された数の日にちだけ現在選択中の日 (currentDay) を移動します。移動が月をまたがる場合でも正しく処理されます。

メソッド: ShowDayOptions(DateTime selectedDay)

選択した日に対するオプション(予定確認、予定追加、戻る)をユーザーに提示し、選択に応じたアクションを実行します。選択肢はカーソルキーで選び、Enterで決定します。

追加の機能メソッド

メソッド: AddNewSchedule(DateTime date)

ユーザーから新しい予定の入力を受け付け、選択した日付にそれを追加します。予定が追加されると、その旨が表示されます。

メソッド: ShowSchedules(DateTime date)

選択された日のすべての予定を表示します。ユーザーはリストから予定を選択して編集するか、新しい予定を追加することができます。

メソッド: EditSchedule(List<string> daySchedules, int index)

選択された予定を編集するための機能です。ユーザーは新しい内容を入力して既存の予定を上書きできます。


メインエントリポイント

public static void Main(string[] args)
{
    var c = new DisplayCalendar();
    c.RunCalendar();
}
  • この部分はプログラムのエントリポイントです。DisplayCalendarクラスのインスタンスを作成し、そのRunCalendarメソッドを呼び出してカレンダー機能を開始します。

DisplayCalendar クラス

このクラスはカレンダーアプリケーションの主要な機能を管理します。

コンストラクタ

public DisplayCalendar()
{
    today = DateTime.Today;
    currentDay = today;
    schedules = new Dictionary<DateTime, List<string>>();
    // 仮の予定データの追加
    schedules[currentDay] = new List<string> { "予定1", "予定2", "予定3" };
}
  • todaycurrentDay 変数は現在の日付で初期化されます。

  • schedules は、日付ごとの予定リストを格納するための辞書です。ここでは現在の日付に仮の予定を追加しています。

RunCalendar メソッド

public void RunCalendar()
{
    bool continueRunning = true;
    while (continueRunning)
    {
        Console.Clear();
        DisplayCalendarMonth();
        continueRunning = ProcessInput();
    }
}


  • このメソッドはカレンダーを表示し続け、ユーザーの入力を処理します。ProcessInputメソッドがfalseを返すまでループします。

DisplayCalendarMonth メソッド

private void DisplayCalendarMonth()
{
    int daysInMonth = DateTime.DaysInMonth(currentDay.Year, currentDay.Month);
    DateTime firstDayOfMonth = new DateTime(currentDay.Year, currentDay.Month, 1);

    Console.WriteLine($"***** {currentDay.Year}{currentDay.Month}月 *****");
    Console.WriteLine(" 日 月 火 水 木 金 土");

    int dayOffset = (int)firstDayOfMonth.DayOfWeek;
    int dayPrinted = 1;

    for (int i = 0; i < 6; i++)
    {
        for (int j = 0; j < 7; j++)
        {
            if (i == 0 && j < dayOffset)
            {
                Console.Write("   ");
            }
            else if (dayPrinted <= daysInMonth)
            {
                if (currentDay.Day == dayPrinted)
                    Console.Write($"[{dayPrinted,2}]");
                else
                    Console.Write($"{dayPrinted,3}");

                dayPrinted++;
            }
        }
        Console.WriteLine();
    }
}
  • 月のカレンダーを表示します。日付は7日間の週として整理され、最初の日から始まります。currentDayがその月の日付を強調表示します。

高度な文法

条件演算子(三項演算子)

csharpCopy code

List<string> daySchedules = schedules.ContainsKey(date) ? schedules[date] : new List<string>();

  • この行は三項演算子を使用しています。これは if-else ステートメントのショートハンドです。条件 (schedules.ContainsKey(date)) が true の場合、schedules[date] を返し、false の場合は new List<string>() を返します。

  • これにより、指定された日付に対する予定が辞書に存在するかどうかをチェックし、存在する場合はそのリストを取得し、存在しない場合は新しい空のリストを作成します。

このプログラムではC#の基本的なデータ構造と制御フローを使用してユーザーインタラクションを実装しており、日付に対する操作(表示、追加、編集)を提供しています。

この記事が気に入ったらサポートをしてみませんか?