Skip to content

Latest commit

 

History

History
247 lines (205 loc) · 7.53 KB

12.md

File metadata and controls

247 lines (205 loc) · 7.53 KB

Pergunta

12 - Cria uma classe chamada Dog. Instâncias desta classe devem ter os seguintes atributos:

  • Peso (double)
  • Altura (double)
  • Cor (string)
  • Saciação (double entre 0 e 1, que corresponde à percentagem de saciação)

Instâncias desta classe devem ter a seguinte funcionalidade:

  • Comer (no máximo até estar cheio/saciado)
  • Fazer necessidades (no mínimo até estar vazio/cheio de fome)
  • Ladrar (deve ser impresso o tipo de ladrar)
  • Correr (deve ser devolvida a velocidade, igual a saciação * 100 / peso)

A classe deve ser implementada com as variáveis de instância, propriedades, construtores e métodos necessários para atingir estes requisitos, usando as melhores práticas para o efeito. Dentro do possível as propriedades devem ser públicas com valores por omissão, auto-implementadas e com set privado (read-only). Todos os nomes usados devem estar em inglês.

Cria também uma classe Program com um método Main() estático para testar todas as funcionalidades da classe Dog.

As classes Dog e Program devem ser completamente documentadas com comentários XML em inglês.

Este enunciado é propositadamente vago e os alunos devem complementar o exercício da forma que acharem melhor, desde de que vá ao encontro do que é pedido.

Soluções

Solução 1

Program.cs

using System;

namespace Dog
{
    /// <summary>
    /// Tests the Dog class, printing the respective variables on the 
    /// console in different circumstances while running 
    /// </summary>
    class Program
    {
        /// <summary>
        /// Tests multiple Dog class methods, printing on the console 
        /// the value of the variables in between them, as well as indicating
        /// the respective dog object it belongs
        /// </summary>
        /// <param name="args">Command-line arguments (not used)</param>
        static void Main(string[] args)
        {
            // Assigning two dog objects
            Dog dog1 = new Dog();
            Dog dog2 = new Dog(57.21, 54.66, "Light Brown");

            // Printing the dog 1 properties
            Console.WriteLine("DOG 1 - Constructor without arguments:\n" +
                $"Weight: {dog1.Weight}\n" +
                $"Height: {dog1.Height}\n" +
                $"Color:  {dog1.Color}");
            // Printing the dog 2 properties
            Console.WriteLine("\nDOG 2 - Constructor with arguments:\n" +
                $"Weight: {dog2.Weight}\n" +
                $"Height: {dog2.Height}\n" +
                $"Color:  {dog2.Color}\n");

            // Test going to the bush without eating
            dog1.GoToTheBush();
            Console.WriteLine($"Dog 1 satiation: {dog1.Satiation}");

            // Test going to the bush after eating
            dog2.Eat();
            dog2.GoToTheBush();
            Console.WriteLine($"Dog 2 satiation: {dog2.Satiation}");

            // Test eat method until satiation is full
            dog1.Eat();
            dog1.Eat();
            dog1.Eat();
            Console.WriteLine($"Dog 1 satiation: {dog1.Satiation}");

            // Know dog 1 speed
            Console.WriteLine($"Dog 1 velocity:  {dog1.Run():#.##}");

            // Know dog 2 speed
            Console.WriteLine($"Dog 2 velocity:  {dog2.Run():#.##}\n");

            // Make them bark
            dog1.Bark();
            dog2.Bark();
        }
    }
}

Dog.cs

using System;

namespace Dog
{
    /// <summary>
    /// Contains what the Dog can do
    /// </summary>
    class Dog
    {
        // Declaring variables
        private Random random = new Random();
        private double satiation;
        private static readonly string[] barks = new string[]
            { "BARK!", "baAAAArk!", "bork!", "BORK!", "Aurf..." };

        /// <summary>
        /// Auto-implemented property represents the chosen dog color, 
        /// with a private set
        /// </summary>
        public string Color { get; private set; }

        /// <summary>
        /// Auto-implemented property represents the dogs height, 
        /// with a private set
        /// </summary>
        public double Height { get; private set; }

        /// <summary>
        /// Auto-implemented property represents the dogs weight, 
        /// with a private set
        /// </summary>
        public double Weight { get; private set; }

        /// <summary>
        /// Property represents the variable satiation and checks if the value
        /// is never bigger than 1
        /// </summary>
        public double Satiation
        {
            get => satiation;

            private set
            {
                if (value <= 1)
                    satiation = value;
                else
                    satiation = 1;
            }
        }

        /// <summary>
        /// Dog constructor with no arguments, sets all to random values
        /// </summary>
        public Dog()
        {
            // Temporary method variables
            string[] colors = new string[]
            { "Orange", "Brown", "White", "Black", "No fur", "Rainbow" };

            string randColor = colors[random.Next(barks.Length)];
            double randWeight, randHeight;

            randWeight =
                random.Next(2, 120) + Math.Round(random.NextDouble(), 2);

            randHeight =
                random.Next(15, 170) + Math.Round(random.NextDouble(), 2);

            // Calling the initialize method using this variables as arguments
            Initialize(randWeight, randHeight, randColor);
        }

        /// <summary>
        /// Dog constructor with arguments
        /// </summary>
        /// <param name="weight">Dogs weight</param>
        /// <param name="height">Dogs height</param>
        /// <param name="color">Dogs color</param>
        public Dog(double weight, double height, string color)
        {
            // Calling the initialize method using inputed
            // variables as arguments
            Initialize(weight, height, color);
        }

        /// <summary>
        /// Initializing variables from the constructors  
        /// </summary>
        /// <param name="weight">Dogs weight</param>
        /// <param name="height">Dogs height</param>
        /// <param name="color">Dogs color</param>
        private void Initialize(double weight, double height, string color)
        {
            satiation = 0;
            Weight = weight;
            Height = height;
            Color = color;
        }

        /// <summary>
        /// Make the dog eat.
        /// Satiation will be incremented by a random number if it is low 
        /// enough
        /// </summary>
        public void Eat()
        {

            double newSatiation = 0.1 + random.NextDouble() * 0.8;
            newSatiation = Math.Round(newSatiation, 1);

            Satiation += newSatiation;
        }

        /// <summary>
        /// Make the dog go to the bush.
        /// If satiation is high enough, it is divided by 2
        /// </summary>
        public void GoToTheBush()
        {
            if (Satiation >= 0.1)
                Satiation /= 2;
        }

        /// <summary>
        /// Make the dog bark using a random string
        /// </summary>
        public void Bark()
        {
            Console.WriteLine(barks[random.Next(barks.Length)]);
        }

        /// <summary>
        /// Make the dog run
        /// Dogs Satiation and weight are used to know at what speed it can go
        /// </summary>
        /// <returns>Speed value</returns>
        public double Run() => satiation * 100 / Weight;
    }
}

Por Tomás Franco