Попытка вернуться к началу консольного приложения - PullRequest
0 голосов
/ 09 января 2019

Я работаю над оценочным произведением, в котором мы должны вывести, находится ли картина в книжной или альбомной ориентации. Я не могу понять, где поставить или даже если цикл будет работать в моем коде для перезапуска, если пользователь вводит недопустимую строку. Мой код выглядит так.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("What is the Height of the Painting?");

        string input = Console.ReadLine();
        int height;

        if (!int.TryParse(input, out height))
        {
            Console.WriteLine("Invalid number. Please make it an integer... e.g 1-9");
        }
        else
        {
            Console.WriteLine("What is the Width of the Painting?");

            string input2 = Console.ReadLine();
            int width;

            if (!int.TryParse(input2, out width))
            {
                Console.WriteLine("Invalid number. Please make it an integer... e.g 1-9");
            }
            else
            {
                var orientation = (height > width ? Orientation.Landscape : Orientation.Portrait);

                Console.WriteLine("Your Painting is currently in the: " + orientation + " orientation");
            }
        }
    }

    public enum Orientation
    {
        Landscape,
        Portrait
    }
}

Любая помощь будет принята с благодарностью.

Ответы [ 2 ]

0 голосов
/ 09 января 2019

Не повторить себя : извлечь метод :

static int ReadInt(string title) {
  int result = 0;

  while (true) {
    Console.WriteLine(title);

    if (int.TryParse(Console.ReadLine(), out result)) 
      return result;

    Console.WriteLine("Invalid number. Please make it an integer... e.g 1-9");
  }
}

Затем используйте его: если вы хотите вычислить один раз :

static void Main(string[] args) {
  int height = ReadInt("What is the Height of the Painting?");
  int width = ReadInt("What is the Width of the Painting?");

  Console.WriteLine(
    $"Your Painting is currently in the: {((height > width ? "portrait" : "landscape")} orientation");
}

Если вы хотите вычислять много раз:

static void Main(string[] args) {
  while (true) {
    int height = ReadInt("What is the Height of the Painting?");
    int width = ReadInt("What is the Width of the Painting?");

    Console.WriteLine(
      $"Your Painting is currently in the: {((height > width ? "portrait" : "landscape")} orientation");

    Console.WriteLine("Would you like to compute another sizes (y/n)?");

    if (string.Equals("n", Console.ReadLine().Trim(), StringComparer.OrdinalIgnoreCase))
      break;
  }
}
0 голосов
/ 09 января 2019

Вы обвиваете все, что хотите повторить. Не забудьте предоставить способ вырваться из этого:

class Program
{
    static void Main(string[] args)
    {

      while(true) { //run forever, we'll break out if the user wants to quit

        Console.WriteLine("What is the Height of the Painting?");

        string input = Console.ReadLine();
        int height;


        if ("int.TryParse(input, out height))
        {
            Console.WriteLine("Invalid number. Please make it an integer... e.g 1-9");
        }
        else
        {
            Console.WriteLine("What is the Width of the Painting?");
            string input2 = Console.ReadLine();
            int width;

            if (!int.TryParse(input2, out width))
            {
                Console.WriteLine("Invalid number. Please make it an integer... e.g 1-9");
            }
            else
            {
                var orientation = (height > width ? Orientation.Landscape : Orientation.Portrait);
                Console.WriteLine("Your Painting is currently in the: " + orientation + " orientation");
            }
        }


        Console.WriteLine("Do another? Enter yes to do another");

        string input = Console.ReadLine();
        if(input != "yes")
        {
          break; //exit loop
        }

      } //end of while loop
    }

    public enum Orientation
        {
            Landscape,
            Portrait

        }
    }
}

Если вас уже научили писать собственные методы, вы можете использовать их для уменьшения повторения кода:

с использованием системы;

class Program
{
    static void Main(string[] args)
    {

        int height = AskForInt("What is the Height of the Painting?");
        int width = AskForInt("What is the Width of the Painting?");

        var orientation = (height > width ? Orientation.Landscape : Orientation.Portrait);

        Console.WriteLine("Your Painting is currently in the: " + orientation + " orientation");

    }

    static int AskForInt(string question) {
        Console.WriteLine(question);

        while (true) //use a loop to keep asking the user if they didn't provide a valid answer
        {
            string input = Console.ReadLine();
            int answer;

            if (!int.TryParse(input, out answer))
            {
                Console.WriteLine("Not a valid integer. Please enter an integer: ");
            }
            else
            {
                return answer; //exit this method, returning the int
            }
        }
    }

    public enum Orientation
    {
        Landscape,
        Portrait

    }
}

Я оставлю этот последний пример зацикленным на себе как упражнение для читателя:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...