0

私は授業を受けていますが、先生は私たちにこれを理解できるかどうか尋ねました. 私は今数時間見てきましたが、それを行う方法が見つかりませんでした。

目標は、displaymenu一度だけ表示することです。アプリはループするため、終了せずに再利用できます。displaymenuは、ユーザーが何をしたいかを選択するためのオプションを表示します。これは皆さんが今まで見た中で最もクリーンなコードではないと思いますが、まだ学習中です。これを行ってまだ 1 週間しか経っていません。それに対する他の提案をいただければ幸いです。

static void Main(string[] args) 
{
    string choice = "";

    do {
        **displayMenu();**      // only want to display once
        choice = getChoice();                
    }
    while (choice != "10");

    {
        Console.ReadLine();
    }      
}

static void displayMenu()
{
    Console.WriteLine("Which shape do you want to work with?"); 
    Console.WriteLine("_____________________________________");
    Console.WriteLine("Press 1 for a circle.");
    Console.WriteLine("Press 2 for an equilateral triangle.");
    Console.WriteLine("Press 3 for a square.");
    Console.WriteLine("Press 4 for a pentagon.");
    Console.WriteLine("Press 5 for a hexagon.");
    Console.WriteLine("Press 6 for a heptagon.");
    Console.WriteLine("Press 7 for a octagon.");
    Console.WriteLine("Press 8 for a nonagon.");
    Console.WriteLine("Press 9 for a decagon.");
    Console.WriteLine("Press 10 to quit.");
}

static string getChoice()
{
    string c = Console.ReadLine();

    if (c == "1")
        circle();
    if (c == "2")
        triangle();
    if (c == "3")
        square();
    if (c == "4")
        polygon(5);
    if (c == "5")
        polygon(6);
    if (c == "6")
        polygon(7);
    if (c == "7")
        polygon(8);
    if (c == "8")
        polygon(9);
    if (c == "9")
        polygon(10);

    return c;
}
4

2 に答える 2

1

選択は数値なので、入力として整数を使用した方がよいのではないでしょうか?

    static void Main(string[] args) 
    {
        do 
        {
            choice = getChoice();                
        }
        while (choice != 10);
        {
            Console.ReadLine();
        }
    }

文字列を int に変換するには、次のように簡単です。

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

ただし、入力が数値でない場合、これによりエラーが発生します。したがって、これが推奨されます:

    static void Main(string[] args) 
    {
        bool isInt;
        int intNumber;
        int choice;

        string stringInput = Console.ReadLine();

        isInt = int.TryParse(stringInput, out intNumber);

        if (!isInt)
        {
            Console.WriteLine("Input is not a number");
        }
        else
        {
            choice = intNumber;
        }
    }
于 2011-11-08T05:13:51.320 に答える