├── Código ├── 00_Revisao │ ├── Media │ │ ├── .vs │ │ │ ├── Media │ │ │ │ ├── v17 │ │ │ │ │ ├── .suo │ │ │ │ │ └── .futdcache.v2 │ │ │ │ ├── DesignTimeBuild │ │ │ │ │ └── .dtbcache.v2 │ │ │ │ └── FileContentIndex │ │ │ │ │ ├── 4154427b-9089-47b2-b9f4-bce47278789b.vsidx │ │ │ │ │ └── ef109868-b78f-4ea9-93bc-812d7e7a81df.vsidx │ │ │ └── ProjectEvaluation │ │ │ │ ├── media.metadata.v7.bin │ │ │ │ └── media.projects.v7.bin │ │ ├── Media.csproj │ │ ├── Program.cs │ │ ├── Media.sln │ │ └── Program2.cs │ └── Produtos │ │ ├── .vs │ │ └── Produtos │ │ │ └── v17 │ │ │ └── .suo │ │ ├── Produtos.csproj │ │ ├── Programa2.cs │ │ ├── Produtos.sln │ │ ├── Produto.cs │ │ └── Program.cs ├── XulambsFoods │ ├── docs │ │ ├── diagramas │ │ │ ├── 01-Pizza.png │ │ │ ├── 02-Pedido.png │ │ │ └── 03-PedidoEntrega.png │ │ └── requisitos.md │ ├── XulambsFoods_2025-1.csproj │ ├── src │ │ ├── IPedido.cs │ │ ├── ComparadorDeGastos.cs │ │ ├── PedidoLotadoException.cs │ │ ├── medalhistas.txt │ │ ├── Ordenador.cs │ │ ├── PedidoEntrega.cs │ │ ├── BaseDados.cs │ │ ├── Cliente.cs │ │ ├── PedidoLocal.cs │ │ ├── Sanduiche.cs │ │ ├── Comida.cs │ │ ├── Pizza.cs │ │ ├── Pedido.cs │ │ ├── PedidoXulambs.cs │ │ └── XulambsFoods.cs │ ├── README.md │ └── XulambsFoods_2025-1.sln ├── 01_Basicos │ ├── Hora │ │ ├── .vs │ │ │ └── Hora │ │ │ │ └── v17 │ │ │ │ └── .futdcache.v2 │ │ ├── Hora.csproj │ │ ├── Hora.sln │ │ ├── Program.cs │ │ └── Hora.cs │ └── Produto │ │ ├── Produto_diagramaInicial.dia │ │ ├── Produto_diagramaInicial.png │ │ ├── Comercio.csproj │ │ ├── Comercio.sln │ │ ├── Program.cs │ │ └── Produto.cs ├── 02_Polimorfismo │ ├── 00_HerancaPessoa │ │ ├── HerancaPessoa.csproj │ │ ├── HerancaPessoa.sln │ │ ├── Administrativo.cs │ │ ├── Program.cs │ │ ├── Professor.cs │ │ ├── Aluno.cs │ │ └── Pessoa.cs │ ├── 01_Polimorfismo_Formas │ │ ├── PoliFiguras.csproj │ │ ├── RetanguloPequeno.cs │ │ ├── PoligonoReto.cs │ │ ├── Quadrado.cs │ │ ├── Retangulo.cs │ │ ├── Circulo.cs │ │ ├── TrianguloRetangulo.cs │ │ ├── PoliFiguras.sln │ │ ├── FormaGeometrica.cs │ │ ├── ConjuntoGeometrico.cs │ │ └── Program.cs │ └── 02_Interfaces_Amplexa │ │ ├── IRegulavel.cs │ │ ├── IDesligavel.cs │ │ ├── POO_C#_Interfaces_Amplexa.csproj │ │ ├── Geladeira.cs │ │ ├── Lampada.cs │ │ ├── Dispositivo.cs │ │ ├── Cafeteira.cs │ │ ├── POO_C#_Interfaces_Amplexa.sln │ │ ├── Amplexa.cs │ │ └── Program.cs └── XulambsFoods_2024-2Tests │ ├── XulambsFoods_2024-2Tests.csproj │ └── src │ ├── SanduicheTests.cs │ ├── PizzaTests.cs │ └── PedidoTests.cs ├── README.md ├── LICENSE └── .gitignore /Código/00_Revisao/Media/.vs/Media/v17/.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/POO-SI/HEAD/Código/00_Revisao/Media/.vs/Media/v17/.suo -------------------------------------------------------------------------------- /Código/00_Revisao/Produtos/.vs/Produtos/v17/.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/POO-SI/HEAD/Código/00_Revisao/Produtos/.vs/Produtos/v17/.suo -------------------------------------------------------------------------------- /Código/XulambsFoods/docs/diagramas/01-Pizza.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/POO-SI/HEAD/Código/XulambsFoods/docs/diagramas/01-Pizza.png -------------------------------------------------------------------------------- /Código/XulambsFoods/docs/diagramas/02-Pedido.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/POO-SI/HEAD/Código/XulambsFoods/docs/diagramas/02-Pedido.png -------------------------------------------------------------------------------- /Código/01_Basicos/Hora/.vs/Hora/v17/.futdcache.v2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/POO-SI/HEAD/Código/01_Basicos/Hora/.vs/Hora/v17/.futdcache.v2 -------------------------------------------------------------------------------- /Código/00_Revisao/Media/.vs/Media/v17/.futdcache.v2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/POO-SI/HEAD/Código/00_Revisao/Media/.vs/Media/v17/.futdcache.v2 -------------------------------------------------------------------------------- /Código/01_Basicos/Produto/Produto_diagramaInicial.dia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/POO-SI/HEAD/Código/01_Basicos/Produto/Produto_diagramaInicial.dia -------------------------------------------------------------------------------- /Código/01_Basicos/Produto/Produto_diagramaInicial.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/POO-SI/HEAD/Código/01_Basicos/Produto/Produto_diagramaInicial.png -------------------------------------------------------------------------------- /Código/XulambsFoods/docs/diagramas/03-PedidoEntrega.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/POO-SI/HEAD/Código/XulambsFoods/docs/diagramas/03-PedidoEntrega.png -------------------------------------------------------------------------------- /Código/00_Revisao/Media/.vs/Media/DesignTimeBuild/.dtbcache.v2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/POO-SI/HEAD/Código/00_Revisao/Media/.vs/Media/DesignTimeBuild/.dtbcache.v2 -------------------------------------------------------------------------------- /Código/00_Revisao/Media/.vs/ProjectEvaluation/media.metadata.v7.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/POO-SI/HEAD/Código/00_Revisao/Media/.vs/ProjectEvaluation/media.metadata.v7.bin -------------------------------------------------------------------------------- /Código/00_Revisao/Media/.vs/ProjectEvaluation/media.projects.v7.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/POO-SI/HEAD/Código/00_Revisao/Media/.vs/ProjectEvaluation/media.projects.v7.bin -------------------------------------------------------------------------------- /Código/00_Revisao/Media/.vs/Media/FileContentIndex/4154427b-9089-47b2-b9f4-bce47278789b.vsidx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/POO-SI/HEAD/Código/00_Revisao/Media/.vs/Media/FileContentIndex/4154427b-9089-47b2-b9f4-bce47278789b.vsidx -------------------------------------------------------------------------------- /Código/00_Revisao/Media/.vs/Media/FileContentIndex/ef109868-b78f-4ea9-93bc-812d7e7a81df.vsidx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/POO-SI/HEAD/Código/00_Revisao/Media/.vs/Media/FileContentIndex/ef109868-b78f-4ea9-93bc-812d7e7a81df.vsidx -------------------------------------------------------------------------------- /Código/00_Revisao/Media/Media.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Código/01_Basicos/Hora/Hora.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Código/00_Revisao/Produtos/Produtos.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Código/01_Basicos/Produto/Comercio.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # POO 2 | 3 | ## Conteúdo da disciplina de Programação Orientada Por Objetos - Sistemas de Informação - PUC Minas São Gabriel 4 | 5 | Branch "main" contém a versão mais atualizada do Restaurante Xulambs e outros exemplos. Cada versão do restaurante está em uma ramificação separada para acompanhamento da evolução do projeto. 6 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/00_HerancaPessoa/HerancaPessoa.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/01_Polimorfismo_Formas/PoliFiguras.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/02_Interfaces_Amplexa/IRegulavel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace POO_C__Interfaces_Amplexa { 8 | internal interface IRegulavel { 9 | public void Regular(int potencia); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/02_Interfaces_Amplexa/IDesligavel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace POO_C__Interfaces_Amplexa { 8 | internal interface IDesligavel { 9 | public bool Ligar(); 10 | public bool Desligar(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Código/XulambsFoods/XulambsFoods_2025-1.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | XulambsFoods_2024_2 7 | enable 8 | enable 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/02_Interfaces_Amplexa/POO_C#_Interfaces_Amplexa.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | POO_C__Interfaces_Amplexa 7 | enable 8 | enable 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Código/XulambsFoods/src/IPedido.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace XulambsFoods_2024_2.src { 8 | public interface IPedido { 9 | public int Adicionar(Comida comida); 10 | public double ValorTaxa(); 11 | 12 | public double ValorItens(); 13 | public string Relatorio(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Código/XulambsFoods/src/ComparadorDeGastos.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace XulambsFoods_2024_2.src { 8 | public class ComparadorDeGastos : Comparer { 9 | public override int Compare(Cliente? x, Cliente? y) { 10 | return (x.TotalGasto() - y.TotalGasto() > 0) ? 1 : -1; 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Código/XulambsFoods/src/PedidoLotadoException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace XulambsFoods_2024_2.src { 8 | public class PedidoLotadoException : InvalidOperationException { 9 | 10 | public PedidoLotadoException() : base() { 11 | 12 | } 13 | 14 | public PedidoLotadoException(string msg) : base(msg) { 15 | 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/01_Polimorfismo_Formas/RetanguloPequeno.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace PoliFiguras 8 | { 9 | public class RetanguloPequeno : Retangulo 10 | { 11 | public RetanguloPequeno() : base(3, 4, 1, 1) { } 12 | 13 | public override double Area() 14 | { 15 | return 7; 16 | } 17 | 18 | public override string ToString() 19 | { 20 | return "Retanglinho de área 12"; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/02_Interfaces_Amplexa/Geladeira.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace POO_C__Interfaces_Amplexa { 8 | internal class Geladeira : Dispositivo, IRegulavel { 9 | private int _potencia; 10 | 11 | public Geladeira(string nome) : base(nome) { 12 | Regular(60); 13 | } 14 | 15 | public void Regular(int potencia) { 16 | if (potencia > 0 && potencia < 101) 17 | _potencia = potencia; 18 | SetEstado($"Geladeira ligada com potência {_potencia}."); 19 | } 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Código/00_Revisao/Produtos/Programa2.cs: -------------------------------------------------------------------------------- 1 | namespace Produtos { 2 | 3 | public class ProgramaDeTeste1 { 4 | static void Mainzinho(string[] args) { 5 | Produto produto1 = new Produto(); 6 | int quantidade; 7 | 8 | produto1.descricao = "Chá mate com gás"; 9 | produto1.precoUnitario = 2.99f; 10 | 11 | Console.WriteLine("Produto disponínel: " + produto1.descricaoProduto()); 12 | 13 | Console.Write("Quer comprar quantos? "); 14 | quantidade = int.Parse(Console.ReadLine()); 15 | Console.WriteLine(quantidade + " " + produto1.descricao + " vão te custar R$ " + 16 | produto1.precoPorLote(quantidade).ToString("0.00")); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/01_Polimorfismo_Formas/PoligonoReto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace PoliFiguras { 8 | public abstract class PoligonoReto : FormaGeometrica { 9 | 10 | protected double _basePoligono; 11 | protected double _alturaPoligono; 12 | 13 | protected PoligonoReto(string desc, double b, double h, int posX, int posY): 14 | base(desc, posX, posY) { 15 | _basePoligono = _alturaPoligono = 0.1; 16 | if (b > 0.1) 17 | _basePoligono = b; 18 | if (h > 0.1) 19 | _alturaPoligono = h; 20 | } 21 | 22 | 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/02_Interfaces_Amplexa/Lampada.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace POO_C__Interfaces_Amplexa { 8 | public class Lampada : Dispositivo, IDesligavel{ 9 | 10 | private bool _ligado; 11 | 12 | public Lampada(string nome) : base(nome) { 13 | Desligar(); 14 | } 15 | 16 | public bool Ligar() { 17 | _ligado = true; 18 | SetEstado("Lâmpada acesa."); 19 | return _ligado; 20 | } 21 | 22 | public bool Desligar() { 23 | _ligado = false; 24 | SetEstado("Lâmpada apagada."); 25 | return _ligado; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/01_Polimorfismo_Formas/Quadrado.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace PoliFiguras { 8 | internal class Quadrado : PoligonoReto { 9 | 10 | public Quadrado(double lado, int posX, int posY) : 11 | base("Quadrado", lado, lado, posX, posY) { 12 | 13 | } 14 | 15 | public override double Area() { 16 | return Math.Pow(_basePoligono, 2.0); 17 | } 18 | 19 | public override double Perimetro() { 20 | return 4 * _basePoligono; 21 | } 22 | 23 | public override string ToString() { 24 | return $"{base.ToString()} | Lado: {_basePoligono:F2}"; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Código/XulambsFoods/README.md: -------------------------------------------------------------------------------- 1 | # Xulambs ~~Pizza~~ Foods 2 | 3 | ## Versão 0.3b - Sanduíches e Pizzas 4 | 5 | A Xulambs Pizza está progredindo rapidamente nos seus negócios locais e para entrega. Agora, querem diversificar seu público oferecendo outras opções de comidas. O primeiro passo nessa direção é a inclusão de _sanduíches_ no cardápio. 6 | 7 | Os sanduíches seguem um modelo de venda similar ao que está dando certo para as pizzas: 8 | - Preço inicial de `R$15`; 9 | - Podem receber até `5` adicionais, custando `R$3` cada; 10 | - Podem fazer parte de um _combo com fritas_ e, neste caso, há um acréscimo de `R$5`. 11 | 12 | Para incentivar a venda de pizzas, que são mais caras, os gestores decidiram criar uma nova regra de preço: a partir do `6° adicional` da pizza, eles terão `50%` de desconto. 13 | 14 | -------------------------------------------------------------------------------- /Código/XulambsFoods/src/medalhistas.txt: -------------------------------------------------------------------------------- 1 | Beatriz Souza 2 | Rebeca Andrade 3 | Ana Patrícia 4 | Duda 5 | Tatiana Weston-Webb 6 | Larissa Pimenta 7 | Rayssa Leal 8 | Flávia Saraiva 9 | Jade Barbosa 10 | Júlia Soares 11 | Lorrane Oliveira 12 | Rafaela Silva 13 | Ketleyn Quadros 14 | Bia Ferreira 15 | Lorena 16 | Antônia 17 | Tarciane 18 | Rafaelle 19 | Duda Sampaio 20 | Tamires 21 | Kerolin 22 | Vitória Yaya 23 | Adriana 24 | Marta 25 | Jheniffer 26 | Tainá 27 | Yasmim 28 | Ludmila 29 | Thaís 30 | Gabi Nunes 31 | Ana Vitória 32 | Gabi Portilho 33 | Priscila 34 | Angelina 35 | Lauren 36 | Luciana 37 | Nyeme Costa 38 | Diana Alecrim 39 | Macris Carneiro 40 | Thaísa Menezes 41 | Rosamaria Montibeller 42 | Roberta Ratzke 43 | Gabi Guimarães 44 | Ana Cristina de Souza 45 | Natália Araújo 46 | Ana Carolina da Silva 47 | Júlia Bergmann 48 | Tainara Santos 49 | Lorenne Teixeira -------------------------------------------------------------------------------- /Código/02_Polimorfismo/01_Polimorfismo_Formas/Retangulo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace PoliFiguras { 8 | public sealed class Retangulo : PoligonoReto { 9 | 10 | public Retangulo(double b, double h, int posX, int posY): 11 | base("Retângulo", b, h, posX, posY) { 12 | 13 | } 14 | 15 | public override double Area() { 16 | return _basePoligono * _alturaPoligono; 17 | } 18 | 19 | public override double Perimetro() { 20 | return 2 * _basePoligono + 2 * _alturaPoligono; 21 | } 22 | 23 | public override string ToString() { 24 | return $"{base.ToString()} | Base: {_basePoligono:F2} | Altura: {_alturaPoligono:F2}"; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/01_Polimorfismo_Formas/Circulo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace PoliFiguras { 8 | public class Circulo : FormaGeometrica{ 9 | private double _raio; 10 | 11 | public Circulo(double raio, int posX, int posY): 12 | base("Círculo", posX, posY) 13 | { 14 | _raio = 0.1; 15 | if (raio > 0.1) 16 | _raio = raio; 17 | } 18 | 19 | public override double Area() { 20 | return Math.PI * Math.Pow(_raio, 2); 21 | } 22 | 23 | public override double Perimetro() { 24 | return 2 * Math.PI * _raio; 25 | } 26 | 27 | public override string ToString() 28 | { 29 | return $"{base.ToString()} | Raio: {_raio:F2}"; 30 | } 31 | 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/02_Interfaces_Amplexa/Dispositivo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace POO_C__Interfaces_Amplexa { 8 | public abstract class Dispositivo { 9 | private string _nome; 10 | private string _estado; 11 | 12 | protected Dispositivo(string nome) { 13 | _nome = nome; 14 | } 15 | 16 | protected void SetEstado(string estado) { 17 | _estado = estado; 18 | } 19 | 20 | public override bool Equals(object? obj) { 21 | Dispositivo outro = (Dispositivo)obj; 22 | return this._nome.Equals(outro._nome); 23 | } 24 | 25 | public override string ToString() { 26 | return this._nome+": "+this._estado; 27 | } 28 | 29 | public override int GetHashCode() { 30 | return _nome.GetHashCode(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Código/XulambsFoods_2024-2Tests/XulambsFoods_2024-2Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | XulambsFoods_2024_2Tests 6 | enable 7 | enable 8 | 9 | false 10 | true 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/01_Polimorfismo_Formas/TrianguloRetangulo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace PoliFiguras { 8 | internal class TrianguloRetangulo : PoligonoReto{ 9 | 10 | public TrianguloRetangulo(double cateto1, double cateto2, int posX, int posY): 11 | base("Tri Ret", cateto1, cateto2, posX, posY) { 12 | 13 | } 14 | 15 | public override double Area() { 16 | return _basePoligono * _alturaPoligono / 2; 17 | } 18 | 19 | public override double Perimetro() { 20 | return _basePoligono + _alturaPoligono + Hipotenusa(); 21 | } 22 | 23 | private double Hipotenusa() { 24 | return Math.Sqrt(Math.Pow(_basePoligono, 2) + Math.Pow(_alturaPoligono, 2)); 25 | } 26 | 27 | public override string ToString() { 28 | return $"{base.ToString()} | Base: {_basePoligono:F2} | Altura: {_alturaPoligono:F2} | Hipotenusa: {Hipotenusa():F2}"; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Joao Caram 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Código/00_Revisao/Media/Program.cs: -------------------------------------------------------------------------------- 1 | namespace Media 2 | { 3 | internal class Program{ 4 | 5 | static void Main(string[] args){ 6 | 7 | float[] vetor; 8 | int tamanhoVetor; 9 | float soma; 10 | float media; 11 | 12 | Console.Clear(); 13 | Console.Write("Qual o tamanho do vetor a ser lido? "); 14 | tamanhoVetor = int.Parse(Console.ReadLine()); 15 | vetor = new float[tamanhoVetor]; 16 | Console.WriteLine(); 17 | 18 | for (int i = 0; i < tamanhoVetor; i++){ 19 | Console.Write("Digite o valor " + (i + 1) + ": "); 20 | vetor[i] = float.Parse(Console.ReadLine()); 21 | } 22 | 23 | soma = 0; 24 | 25 | for (int i = 0; i < tamanhoVetor; i++) { 26 | soma += vetor[i]; 27 | } 28 | 29 | media = soma / tamanhoVetor; 30 | 31 | Console.WriteLine("A média dos valores do vetor é de " + media.ToString("0.##")); 32 | Console.ReadKey(); 33 | 34 | 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/02_Interfaces_Amplexa/Cafeteira.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace POO_C__Interfaces_Amplexa { 8 | internal class Cafeteira : Dispositivo, IDesligavel, IRegulavel { 9 | private bool _ligado; 10 | private int _potencia; 11 | 12 | public Cafeteira(string nome) : base(nome) { 13 | Regular(0); 14 | SetEstado("Cafeteira desligada"); 15 | } 16 | 17 | public bool Ligar() { 18 | _ligado = true; 19 | Regular(50); 20 | return _ligado; 21 | } 22 | 23 | public bool Desligar() { 24 | _ligado = false; 25 | SetEstado("Cafeteira desligada."); 26 | return _ligado; 27 | } 28 | 29 | public void Regular(int potencia) { 30 | if (_ligado) { 31 | if (potencia >= 0 && potencia < 101) 32 | _potencia = potencia; 33 | } 34 | SetEstado($"Cafeteira ligada com potência {_potencia}."); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Código/01_Basicos/Hora/Hora.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.8.34525.116 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Hora", "Hora.csproj", "{BFDD7799-43F4-44B5-B962-D6AE9452548C}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {BFDD7799-43F4-44B5-B962-D6AE9452548C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {BFDD7799-43F4-44B5-B962-D6AE9452548C}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {BFDD7799-43F4-44B5-B962-D6AE9452548C}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {BFDD7799-43F4-44B5-B962-D6AE9452548C}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {C5676B77-C9E2-4E4A-A49B-3C9F0E08590B} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Código/00_Revisao/Media/Media.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.8.34330.188 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Media", "Media.csproj", "{34BC7B1B-615E-437C-A726-07AA98E55160}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {34BC7B1B-615E-437C-A726-07AA98E55160}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {34BC7B1B-615E-437C-A726-07AA98E55160}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {34BC7B1B-615E-437C-A726-07AA98E55160}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {34BC7B1B-615E-437C-A726-07AA98E55160}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {A15FAAF6-FFE9-4C64-AEFC-A3CD75F4643B} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Código/00_Revisao/Produtos/Produtos.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.8.34330.188 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Produtos", "Produtos.csproj", "{8E1A48C1-3953-431D-859D-9974EC2AC818}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {8E1A48C1-3953-431D-859D-9974EC2AC818}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {8E1A48C1-3953-431D-859D-9974EC2AC818}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {8E1A48C1-3953-431D-859D-9974EC2AC818}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {8E1A48C1-3953-431D-859D-9974EC2AC818}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {804265FD-CD2E-4E29-8214-4D726CBB3D84} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Código/01_Basicos/Produto/Comercio.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.8.34525.116 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Comercio", "Comercio.csproj", "{8A40AFB9-709F-4DE3-A494-C5C03EFDB9E4}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {8A40AFB9-709F-4DE3-A494-C5C03EFDB9E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {8A40AFB9-709F-4DE3-A494-C5C03EFDB9E4}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {8A40AFB9-709F-4DE3-A494-C5C03EFDB9E4}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {8A40AFB9-709F-4DE3-A494-C5C03EFDB9E4}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {99FB263F-FA57-4B2D-9750-134BC5C3485C} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/00_HerancaPessoa/HerancaPessoa.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.8.34330.188 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HerancaPessoa", "HerancaPessoa.csproj", "{CE99727F-8196-4D6C-9765-773A5628AA43}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {CE99727F-8196-4D6C-9765-773A5628AA43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {CE99727F-8196-4D6C-9765-773A5628AA43}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {CE99727F-8196-4D6C-9765-773A5628AA43}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {CE99727F-8196-4D6C-9765-773A5628AA43}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {C2D6799F-E456-4983-B039-1B282233AE27} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/01_Polimorfismo_Formas/PoliFiguras.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.9.34701.34 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PoliFiguras", "PoliFiguras.csproj", "{97779E86-AB2E-424D-BD89-CCA8DB91326E}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {97779E86-AB2E-424D-BD89-CCA8DB91326E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {97779E86-AB2E-424D-BD89-CCA8DB91326E}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {97779E86-AB2E-424D-BD89-CCA8DB91326E}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {97779E86-AB2E-424D-BD89-CCA8DB91326E}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {2108515E-A21E-4B4E-B722-023DD10C9AAA} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/02_Interfaces_Amplexa/POO_C#_Interfaces_Amplexa.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.9.34701.34 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "POO_C#_Interfaces_Amplexa", "POO_C#_Interfaces_Amplexa.csproj", "{FA741D41-E2B1-48E3-BC58-07C5CAE8A459}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {FA741D41-E2B1-48E3-BC58-07C5CAE8A459}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {FA741D41-E2B1-48E3-BC58-07C5CAE8A459}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {FA741D41-E2B1-48E3-BC58-07C5CAE8A459}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {FA741D41-E2B1-48E3-BC58-07C5CAE8A459}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {2CE08AE3-0B0F-475D-BCCB-6B7BE1CC686D} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Código/XulambsFoods_2024-2Tests/src/SanduicheTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using XulambsFoods_2024_2.src; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace XulambsFoods_2024_2.src.Tests { 10 | [TestClass()] 11 | public class SanduicheTests { 12 | static Sanduiche sanduiche; 13 | 14 | [TestInitialize] 15 | public void inicializar() { 16 | sanduiche = new Sanduiche(); 17 | } 18 | 19 | 20 | [TestMethod()] 21 | public void CalcularValorFinal() { 22 | sanduiche.AdicionarIngredientes(3); 23 | Assert.AreEqual(24d, sanduiche.ValorFinal()); 24 | } 25 | 26 | [TestMethod()] 27 | public void ValorFinalComCombo() { 28 | sanduiche = new Sanduiche(true); 29 | sanduiche.AdicionarIngredientes(3); 30 | Assert.AreEqual(29d, sanduiche.ValorFinal()); 31 | } 32 | 33 | 34 | [TestMethod()] 35 | public void NotaDeCompraTest() { 36 | string nota = sanduiche.NotaDeCompra(); 37 | Assert.IsTrue(nota.Contains("0 ingredientes") && 38 | (nota.Contains("15,00"))); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Código/00_Revisao/Media/Program2.cs: -------------------------------------------------------------------------------- 1 | namespace Media { 2 | internal class Program2 { 3 | 4 | static int definirTamanho() { 5 | Console.Clear(); 6 | Console.Write("Qual o tamanho do vetor a ser lido? "); 7 | return int.Parse(Console.ReadLine()); 8 | } 9 | 10 | static void lerVetorFloat(float[] vet) { 11 | for (int i = 0; i < vet.Length; i++) { 12 | Console.Write("Digite o valor " + (i + 1) + ": "); 13 | vet[i] = float.Parse(Console.ReadLine()); 14 | } 15 | } 16 | 17 | static float somaVetorFloat(float[] vet) { 18 | float soma = 0; 19 | for (int i = 0; i < vet.Length; i++) { 20 | soma += vet[i]; 21 | } 22 | return soma; 23 | } 24 | 25 | static float mediaVetorFloat(float[] vet) { 26 | float soma = somaVetorFloat(vet); 27 | return soma / vet.Length; 28 | } 29 | 30 | static void Main(string[] args) { 31 | 32 | float[] vetor; 33 | float media; 34 | 35 | vetor = new float[definirTamanho()]; 36 | lerVetorFloat(vetor); 37 | media = mediaVetorFloat(vetor) ; 38 | 39 | Console.WriteLine("A média dos valores do vetor é de " + media.ToString("0.##")); 40 | Console.ReadKey(); 41 | 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/01_Polimorfismo_Formas/FormaGeometrica.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace PoliFiguras { 8 | public abstract class FormaGeometrica{ 9 | private int _coordX; 10 | private int _coordY; 11 | private string _descricao; 12 | 13 | protected FormaGeometrica(string desc, int posX, int posY) { 14 | _coordX = posX > 0 ? posX : 1; 15 | _coordY = posY > 0 ? posY : 1; 16 | _descricao = desc; 17 | 18 | } 19 | 20 | 21 | public bool TemAreaMaiorQue(FormaGeometrica outra) { 22 | return Area() > outra.Area(); 23 | } 24 | 25 | public override string ToString() { 26 | return $"{_descricao,10} -> Área: {Area():00.00} | Perímetro: {Perimetro():F2}"; 27 | } 28 | 29 | public override int GetHashCode() { 30 | return (_descricao+_coordX.ToString()+_coordY.ToString()).GetHashCode(); 31 | } 32 | 33 | public override bool Equals(object? obj) { 34 | FormaGeometrica outro = obj as FormaGeometrica; 35 | return (Area() == outro.Area() 36 | && _descricao.Equals(outro._descricao)); 37 | } 38 | 39 | public abstract double Area(); 40 | public abstract double Perimetro(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Código/XulambsFoods/XulambsFoods_2025-1.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.9.34902.65 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "XulambsFoods_2025-1", "XulambsFoods_2025-1.csproj", "{D5E60CF8-558E-4EAD-A2C1-2E9B68CAEDA7}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XulambsFoods_2024-2Tests", "..\XulambsFoods_2024-2Tests\XulambsFoods_2024-2Tests.csproj", "{95294845-ACCB-4937-81FC-7DCEF38F426B}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {D5E60CF8-558E-4EAD-A2C1-2E9B68CAEDA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {D5E60CF8-558E-4EAD-A2C1-2E9B68CAEDA7}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {D5E60CF8-558E-4EAD-A2C1-2E9B68CAEDA7}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {D5E60CF8-558E-4EAD-A2C1-2E9B68CAEDA7}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {95294845-ACCB-4937-81FC-7DCEF38F426B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {95294845-ACCB-4937-81FC-7DCEF38F426B}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {95294845-ACCB-4937-81FC-7DCEF38F426B}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {95294845-ACCB-4937-81FC-7DCEF38F426B}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {A037A002-6D7C-4883-AA83-4D6DAF348340} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /Código/XulambsFoods_2024-2Tests/src/PizzaTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using XulambsFoods_2024_2.src; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace XulambsFoods_2024_2.src.Tests { 10 | [TestClass()] 11 | public class PizzaTests { 12 | static Pizza pizza; 13 | 14 | [TestInitialize] 15 | public void SetUp() { 16 | pizza = new Pizza(); 17 | } 18 | 19 | [TestMethod()] 20 | public void CriarPizzaVazia() { 21 | Assert.IsTrue(pizza.NotaDeCompra().Contains("0 ingredientes")); 22 | } 23 | 24 | [TestMethod()] 25 | public void CriarPizzarComIngredientes() { 26 | pizza = new Pizza(2); 27 | Assert.IsTrue(pizza.NotaDeCompra().Contains("2 ingredientes")); 28 | } 29 | 30 | [TestMethod()] 31 | public void CalculaValorCorretamente() { 32 | pizza.AdicionarIngredientes(2); 33 | Assert.AreEqual(39d, pizza.ValorFinal()); 34 | } 35 | 36 | [TestMethod()] 37 | public void AdicionaIngredientesCorretamente() { 38 | pizza = new Pizza(); 39 | Assert.AreEqual(3, pizza.AdicionarIngredientes(3)); 40 | } 41 | 42 | [TestMethod()] 43 | public void NaoPodeAdicionarIngredientesAlemDoMaximo() { 44 | pizza = new Pizza(6); 45 | Assert.AreEqual(6, pizza.AdicionarIngredientes(3)); 46 | } 47 | 48 | [TestMethod()] 49 | public void GeraNotaDeCompraComDetalhes() { 50 | pizza = new Pizza(6); 51 | Assert.IsTrue(pizza.NotaDeCompra().Contains("6 ingredientes")); 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /Código/02_Polimorfismo/00_HerancaPessoa/Administrativo.cs: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2025 João Caram 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | namespace HerancaPessoa 25 | { 26 | public class Administrativo : Pessoa 27 | { 28 | 29 | 30 | private static double salarioBase; 31 | private double valorGratificacao; 32 | 33 | public Administrativo(string nome, DateOnly nascimento, string documento, string email): 34 | base(nome, nascimento, documento, email) 35 | { 36 | 37 | } 38 | 39 | public double salarioBruto() 40 | { 41 | return salarioBase + valorGratificacao; 42 | } 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Código/XulambsFoods_2024-2Tests/src/PedidoTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using XulambsFoods_2024_2.src; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace XulambsFoods_2024_2.src.Tests { 10 | [TestClass()] 11 | public class PedidoTests { 12 | static Pedido pedido; 13 | static Pizza pizzaCom2Ingredientes; 14 | static Pizza pizzaSemIngredientes; 15 | 16 | [TestInitialize] 17 | public void SetUp() { 18 | pizzaCom2Ingredientes = new Pizza(2); 19 | pizzaSemIngredientes = new Pizza(); 20 | pedido = new PedidoLocal(); 21 | } 22 | 23 | [TestMethod()] 24 | public void AdicionaPizzaCorretamente() { 25 | Assert.AreEqual(1, pedido.Adicionar(pizzaCom2Ingredientes)); 26 | } 27 | 28 | [TestMethod()] 29 | public void naoAdicionaPizzaEmPedidoFechado() { 30 | pedido.Adicionar(pizzaCom2Ingredientes); 31 | pedido.FecharPedido(); 32 | Assert.AreEqual(1, pedido.Adicionar(pizzaSemIngredientes)); 33 | } 34 | 35 | [TestMethod()] 36 | public void calculaPrecoCorretamente() { 37 | pedido.Adicionar(pizzaCom2Ingredientes); 38 | pedido.Adicionar(pizzaSemIngredientes); 39 | Assert.AreEqual(68d, pedido.PrecoAPagar(), 0.01); 40 | } 41 | 42 | [TestMethod()] 43 | public void relatorioContemDetalhes() { 44 | pedido.Adicionar(pizzaCom2Ingredientes); 45 | pedido.Adicionar(pizzaSemIngredientes); 46 | string relatorio = pedido.Relatorio(); 47 | Assert.IsTrue(relatorio.Contains("29,00")); 48 | Assert.IsTrue(relatorio.Contains("39,00")); 49 | Assert.IsTrue(relatorio.Contains("68,00")); 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /Código/XulambsFoods/src/Ordenador.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace XulambsFoods_2024_2.src { 8 | public class Ordenador{ 9 | 10 | private T[] _dados; 11 | private Comparer _meuComparador; 12 | 13 | public Ordenador(T[] dados) { 14 | _dados = dados; 15 | _meuComparador = Comparer.Default; 16 | } 17 | 18 | public Ordenador(T[] dados, Comparer comparador) { 19 | _dados = dados; 20 | _meuComparador = comparador; 21 | } 22 | 23 | public T[] ordenar() { 24 | _dados = QuickSort(_dados, 0, _dados.Length-1); 25 | return _dados; 26 | } 27 | 28 | private T[] QuickSort(T[] dados, int inicio, int fim) { 29 | if(fim > inicio) { 30 | int particao = Particao(dados, inicio, fim); 31 | dados = QuickSort(dados, inicio, particao-1); 32 | dados = QuickSort(dados, particao+1, fim); 33 | } 34 | return dados; 35 | } 36 | 37 | private int Particao(T[] dados, int inicio, int fim) { 38 | T pivot = dados[fim]; 39 | 40 | int particao = inicio - 1; 41 | 42 | for (int i = inicio; i < fim; i++) 43 | { 44 | if (_meuComparador.Compare(dados[i], pivot) < 0) { 45 | particao++; 46 | T temporario = dados[i]; 47 | dados[i] = dados[particao]; 48 | dados[particao] = temporario; 49 | } 50 | } 51 | particao++; 52 | T tempPivot = dados[fim]; 53 | dados[fim] = dados[particao]; 54 | dados[particao] = tempPivot; 55 | return particao; 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Código/01_Basicos/Hora/Program.cs: -------------------------------------------------------------------------------- 1 | namespace Hora { 2 | 3 | /** 4 | * App principal apenas para teste da classe Hora 5 | */ 6 | internal class Program { 7 | static void Main(string[] args) { 8 | Hora hora; 9 | Hora hora2; 10 | int horas; 11 | int minutos; 12 | int segundos; 13 | int incremento; 14 | string horaDoUsuario; 15 | 16 | Console.Write("Por favor, digite um horário válido (HH:MM:SS): "); 17 | horaDoUsuario = Console.ReadLine(); 18 | 19 | string[] detalhesHora = horaDoUsuario.Split(":"); 20 | horas = int.Parse(detalhesHora[0]); 21 | minutos = int.Parse(detalhesHora[1]); 22 | segundos = int.Parse(detalhesHora[2]); 23 | 24 | hora = new Hora(); 25 | hora.Ajustar(horas, minutos, segundos); 26 | 27 | Console.Write("Sua hora escolhida: "); 28 | Console.WriteLine(hora.HoraFormatada()); 29 | 30 | Console.Write("\nPor favor, digite um incremento em segundos positivos: "); 31 | incremento = int.Parse(Console.ReadLine()); 32 | 33 | hora2 = hora.Incrementar(incremento); 34 | 35 | Console.WriteLine($"{hora.HoraFormatada()} é sua hora original e {hora2.HoraFormatada()} " + 36 | $"é sua hora com incremento de {incremento} segundos"); 37 | 38 | 39 | Console.Write($"{hora.HoraFormatada()} está na frente de {hora2.HoraFormatada()}? "); 40 | Console.WriteLine(hora.EstahNaFrenteDe(hora2)); 41 | 42 | Console.Write($"{hora2.HoraFormatada()} está na frente de {hora.HoraFormatada()}? "); 43 | Console.WriteLine(hora2.EstahNaFrenteDe(hora)); 44 | 45 | Console.Write("Ajustando a hora para 19:08:24: "); 46 | hora.Ajustar(19, 8, 24); 47 | Console.WriteLine(hora.HoraFormatada()); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Código/XulambsFoods/src/PedidoEntrega.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace XulambsFoods_2024_2.src 8 | { 9 | internal class PedidoEntrega : IPedido 10 | { 11 | private const int MaxEntrega = 2; 12 | private readonly double[] TaxasEntrega = { 0, 5, 8 }; 13 | private readonly double[] DistanciasEntrega = { 4, 8, double.MaxValue }; 14 | 15 | private double _distanciaEntrega; 16 | private BaseDados _comidas; 17 | 18 | 19 | public PedidoEntrega(double distancia) 20 | { 21 | 22 | if (distancia < 0.1) distancia = 0.1; 23 | _distanciaEntrega = distancia; 24 | _comidas = new BaseDados(); 25 | } 26 | 27 | public int Adicionar(Comida comida) 28 | { 29 | if (_comidas.Quantidade() == MaxEntrega) 30 | throw new PedidoLotadoException($"Máximo de {MaxEntrega} comidas em pedido para entrega."); 31 | _comidas.Add(comida); 32 | return _comidas.Quantidade(); 33 | } 34 | 35 | 36 | public double ValorItens() { 37 | return _comidas.Totalizador(c => c.ValorFinal()); 38 | } 39 | 40 | public double ValorTaxa() 41 | { 42 | double taxa = 0d; 43 | for (int i = DistanciasEntrega.Length - 1; i >= 0; i--) 44 | { 45 | if (_distanciaEntrega <= DistanciasEntrega[i]) 46 | taxa = TaxasEntrega[i]; 47 | } 48 | return taxa; 49 | } 50 | 51 | public string Relatorio() 52 | { 53 | StringBuilder sb = new StringBuilder(" - ENTREGA\n"); 54 | sb.AppendLine("============================="); 55 | int i = 1; 56 | 57 | sb.AppendLine(_comidas.RelatorioOrdenado()); 58 | 59 | sb.AppendLine($"TAXA ENTREGA : {ValorTaxa():C2}"); 60 | return sb.ToString(); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/01_Polimorfismo_Formas/ConjuntoGeometrico.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | 3 | namespace PoliFiguras 4 | { 5 | internal class ConjuntoGeometrico 6 | { 7 | private List formas; 8 | private int capacidade; 9 | 10 | public ConjuntoGeometrico(int tamanho) 11 | { 12 | capacidade = 1; 13 | if (tamanho > 1) 14 | capacidade = tamanho; 15 | formas = new List(capacidade); 16 | } 17 | 18 | public void AddForma(FormaGeometrica nova) 19 | { 20 | if (nova != null && formas.Count < capacidade) 21 | { 22 | formas.Add(nova); 23 | } 24 | } 25 | 26 | public FormaGeometrica Buscar(FormaGeometrica outra) 27 | { 28 | bool achou = false; 29 | int pos = 0; 30 | FormaGeometrica achada = null; 31 | while(!achou && pos < formas.Count) 32 | { 33 | if (formas.ElementAt(pos).Equals(outra)) { 34 | achou = true; 35 | achada = formas.ElementAt(pos); 36 | } 37 | else 38 | pos++; 39 | } 40 | return achada; 41 | } 42 | 43 | public FormaGeometrica MaiorDeTodas() { 44 | FormaGeometrica resposta = null; 45 | if(formas.Count > 0) { 46 | resposta = formas.ElementAt(0); 47 | for(int i=1; i< formas.Count; i++) { 48 | if (formas.ElementAt(i).TemAreaMaiorQue(resposta)) 49 | resposta = formas.ElementAt(i); 50 | } 51 | } 52 | return resposta; 53 | 54 | } 55 | 56 | public override string ToString() 57 | { 58 | StringBuilder relat = new StringBuilder("Conjunto com " + formas.Count + " formas geométricas\n"); 59 | foreach(FormaGeometrica forma in formas) 60 | { 61 | relat.AppendLine(forma.ToString()); 62 | } 63 | return relat.ToString(); 64 | } 65 | 66 | 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Código/01_Basicos/Produto/Program.cs: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2022-4 João Caram 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | //Regra 1: Não Viaje 26 | //Regra 2: Não interessa como o método resolve o problema 27 | 28 | namespace Comercio { 29 | 30 | internal class Program { 31 | static void Main(string[] args) { 32 | Produto primeiroProduto = new Produto(); 33 | int quantidade; 34 | 35 | primeiroProduto.registrar("Chá mate com gás", 2.99); 36 | 37 | Console.WriteLine("Produto disponível: "+ primeiroProduto.ToString()); 38 | 39 | primeiroProduto.reajustar(3.25); 40 | 41 | 42 | Console.WriteLine("Produto disponível: " + primeiroProduto.ToString()); 43 | Console.Write("Quantos você quer comprar? "); 44 | quantidade = int.Parse(Console.ReadLine()); 45 | 46 | Console.WriteLine(quantidade + " produtos vão custar R$ " 47 | + primeiroProduto.valorLote(quantidade)); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/02_Interfaces_Amplexa/Amplexa.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Runtime.InteropServices; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace POO_C__Interfaces_Amplexa { 10 | internal class Amplexa { 11 | private Dictionary _dispositivos; 12 | private string _nome; 13 | 14 | public Amplexa(string nome) { 15 | _nome = nome; 16 | _dispositivos = new Dictionary(); 17 | } 18 | 19 | public bool Ligar(string nome) { 20 | IDesligavel? disp = Localizar(nome) as IDesligavel; 21 | 22 | bool resposta = false; 23 | 24 | if (disp != null) { 25 | resposta = disp.Ligar(); 26 | } 27 | 28 | return resposta; 29 | } 30 | 31 | public bool Desligar(string nome) { 32 | IDesligavel? disp = Localizar(nome) as IDesligavel; 33 | 34 | bool resposta = false; 35 | 36 | if (disp != null) { 37 | resposta = disp.Desligar(); 38 | } 39 | 40 | return resposta; 41 | } 42 | 43 | public void Regular(string nome, int potencia) { 44 | Dispositivo? d = Localizar(nome); 45 | IRegulavel? disp = d as IRegulavel; 46 | 47 | if (disp != null) { 48 | disp.Regular(potencia); 49 | } 50 | } 51 | 52 | public void AddDispositivo(Dispositivo novo) { 53 | _dispositivos.Add(novo.GetHashCode(), novo); 54 | } 55 | 56 | private Dispositivo? Localizar(string nome) { 57 | Dispositivo? disp; 58 | _dispositivos.TryGetValue(nome.GetHashCode(), out disp); 59 | return disp; 60 | } 61 | 62 | public override string ToString() { 63 | StringBuilder disp = new StringBuilder(_nome + " controlando:\n"); 64 | foreach (Dispositivo item in _dispositivos.Values) 65 | { 66 | disp.AppendLine(item.ToString()); 67 | } 68 | return disp.ToString(); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Código/XulambsFoods/src/BaseDados.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace XulambsFoods_2024_2.src 9 | { 10 | //LINQ - Language-Integrated Query 11 | 12 | public class BaseDados 13 | { 14 | private Dictionary dados; 15 | 16 | public BaseDados() 17 | { 18 | dados = new Dictionary(); 19 | } 20 | 21 | public int Quantidade() 22 | { 23 | return dados.Count; 24 | } 25 | 26 | public void Add(T novoDado) 27 | { 28 | dados.Add(novoDado.GetHashCode(), novoDado); 29 | } 30 | 31 | public T Localizar(int id) 32 | { 33 | return dados.GetValueOrDefault(id); 34 | } 35 | 36 | public string RelatorioOrdenado() { 37 | return RelatorioOrdenado(Comparer.Default); 38 | } 39 | 40 | public string RelatorioOrdenado(Comparison comparison) { 41 | return RelatorioOrdenado(Comparer.Create(comparison)); 42 | } 43 | 44 | public string RelatorioOrdenado(Comparer comparador) { 45 | StringBuilder relat = new StringBuilder(); 46 | T[] dadosOrd = new T[dados.Count]; 47 | 48 | Array.Copy(dados.Values.ToArray(), dadosOrd, dados.Count); 49 | Ordenador qSort = new Ordenador(dadosOrd, comparador); 50 | dadosOrd = qSort.ordenar(); 51 | 52 | foreach (T item in dadosOrd) { 53 | relat.AppendLine(item.ToString()); 54 | } 55 | relat.Append("=================="); 56 | return relat.ToString(); 57 | } 58 | 59 | public double Totalizador(Func funcaoSomadora) { 60 | double valor = 0d; 61 | foreach(T dado in dados.Values) { 62 | valor += funcaoSomadora.Invoke(dado); 63 | } 64 | return valor; 65 | } 66 | 67 | public void Processar(Action acao) { 68 | foreach (T dado in dados.Values) { 69 | acao.Invoke(dado); 70 | } 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/02_Interfaces_Amplexa/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | namespace POO_C__Interfaces_Amplexa { 4 | internal class Program { 5 | static int numero = 1; //para id dos dispositivos 6 | 7 | 8 | public static Dispositivo CriarDispositivo(String qual) { 9 | Dispositivo novo = qual.ToLower() switch { 10 | "lampada" => new Lampada("L" + numero), 11 | "cafeteira" => new Cafeteira("C" + numero), 12 | "geladeira" => new Geladeira("G" + numero), 13 | }; 14 | numero++; 15 | return novo; 16 | } 17 | 18 | static void Main(string[] args) { 19 | 20 | Amplexa assistente = new Amplexa("Faz Tudo"); 21 | for (int i = 0; i < 6; i++) { 22 | Dispositivo lamp = CriarDispositivo("lampada"); 23 | assistente.AddDispositivo(lamp); 24 | } 25 | 26 | Console.WriteLine("=====INICIO====="); 27 | Console.WriteLine(assistente); 28 | Console.ReadLine(); 29 | 30 | Console.Clear(); 31 | Console.WriteLine("=====LIGANDO DISPOSITIVOS====="); 32 | assistente.Ligar("L5"); 33 | Console.WriteLine(assistente); 34 | Console.ReadLine(); 35 | 36 | Console.Clear(); 37 | Console.WriteLine("=====ADICIONANDO E LIGANDO CAFETEIRAS====="); 38 | assistente.AddDispositivo(CriarDispositivo("cafeteira")); 39 | assistente.AddDispositivo(CriarDispositivo("cafeteira")); 40 | assistente.Ligar("C7"); 41 | Console.WriteLine(assistente); 42 | Console.ReadLine(); 43 | 44 | Console.Clear(); 45 | Console.WriteLine("=====ADICIONANDO GELADEIRA====="); 46 | assistente.AddDispositivo(CriarDispositivo("GELADEIRA")); 47 | Console.WriteLine(assistente); 48 | Console.ReadLine(); 49 | 50 | Console.Clear(); 51 | Console.WriteLine("=====REGULANDO CAFETEIRAS E GELADEIRAS====="); 52 | assistente.Ligar("C8"); 53 | assistente.Regular("G9", 77); 54 | assistente.Regular("C8", 93); 55 | Console.WriteLine(assistente); 56 | Console.ReadLine(); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Código/XulambsFoods/src/Cliente.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace XulambsFoods_2024_2.src 8 | { 9 | public class Cliente : IComparable 10 | { 11 | private static int _ultimoID = 0; 12 | private int _id; 13 | private string _nome; 14 | private Queue _pedidos; 15 | 16 | public Cliente(string nome) 17 | { 18 | if (nome.Length == 0) 19 | nome = "Cliente anônimo"; 20 | _nome = nome; 21 | _id = ++_ultimoID; 22 | _pedidos = new Queue(); 23 | } 24 | 25 | public int CompareTo(object? obj) 26 | { 27 | Cliente outro = obj as Cliente; 28 | return _nome.CompareTo(outro._nome); 29 | } 30 | 31 | public int RegistrarPedido(Pedido novo) 32 | { 33 | _pedidos.Enqueue(novo); 34 | return _pedidos.Count; 35 | } 36 | 37 | public string RelatorioPedidos() 38 | { 39 | StringBuilder relat = new StringBuilder($"Cliente {_nome} - {_id}"); 40 | foreach (Pedido p in _pedidos) 41 | relat.AppendLine(p.ToString()); 42 | relat.Append($"\nTotal gasto pelo cliente: {TotalGasto():C2}"); 43 | return relat.ToString(); 44 | } 45 | 46 | public double TotalGasto() 47 | { 48 | //double valor = 0d; 49 | //foreach (Pedido p in _pedidos) 50 | // valor += p.PrecoAPagar(); 51 | //return valor; 52 | return _pedidos.Sum(ped => ped.PrecoAPagar()); 53 | } 54 | 55 | public override int GetHashCode() { 56 | return _id; 57 | } 58 | 59 | public override bool Equals(object? obj) { 60 | bool resposta = false; 61 | Cliente outro = obj as Cliente; 62 | if (obj != null) 63 | resposta = (_id == outro._id); 64 | return resposta; 65 | } 66 | 67 | public override string ToString() { 68 | return $"{_nome} ({_id}) já gastou {TotalGasto():C2} no Xulambs Foods."; 69 | } 70 | 71 | public void fidelizarCliente(string nomePrograma) { 72 | _nome += " " + nomePrograma; 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/00_HerancaPessoa/Program.cs: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2025 João Caram 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | namespace HerancaPessoa 25 | { 26 | internal class Program 27 | { 28 | static void Main(string[] args) 29 | { 30 | List pessoas = new List(20); 31 | 32 | Pessoa aluno = new Aluno("Aluno Espantado", DateOnly.Parse("04-11-2006"), "Al1", "aluno@aluno.com", 1250d); 33 | aluno.SetCargaHoraria(430); 34 | 35 | Pessoa prof = new Professor("Professor", DateOnly.Parse("05-07-1989"), "Pr1", "prof@prof.com"); 36 | prof.SetCargaHoraria(32); 37 | 38 | pessoas.Add(new Pessoa("Pessoa Feliz", DateOnly.Parse("05-04-2004"), "Pe1", "pessoa@pessoa.com")); 39 | pessoas.Add(aluno); 40 | pessoas.Add(prof); 41 | 42 | Console.WriteLine("Todo mundo:"); 43 | foreach (Pessoa p in pessoas) 44 | { 45 | Console.WriteLine(p.Relatorio()); 46 | } 47 | 48 | Console.WriteLine("\nMensalidade do aluno: (CUIDADO!!!!)"); 49 | double valor = ((Aluno)pessoas[1]).ValorMensalidade(); 50 | Console.WriteLine($"{valor:C2}"); 51 | 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Código/XulambsFoods/docs/requisitos.md: -------------------------------------------------------------------------------- 1 | # Xulambs ~~Pizza~~ Foods 2 | 3 | ## Versão 0.1 - Vendendo Pizzas 4 | 5 | Xulambs Pizza é uma pizzaria que será inaugurada em breve, com grandes expectativas. Inicialmente, o negócio precisa automatizar o cálculo do preço de venda das pizzas. O modelo de vendas segue uma lógica simplificada: 6 | 7 | 1. Não existem pizzas de sabores pré-definidos. 8 | 1. A pizza tem preço inicial de `R$29`. 9 | 1. A pizza pode ter até `8` ingredientes adicionais. 10 | 1. Os adicionais têm custo fixo: cada um custa `R$5`. 11 | 12 | O **Sistema Xulambs Pizza** precisa permitir registrar vendas de pizzas isoladas e emitir um cupom de venda (relatório) para cada uma, contendo sua descrição e valores a serem pagos. 13 | 14 | ## Versão 0.2 - A pizzaria e seus pedidos 15 | 16 | A pizzaria percebeu que é melhor agrupar as vendas de pizzas em pedidos. Foram levantados os requisitos: 17 | 18 | 1. Um pedido deve ter um identificador único. 19 | 1. Um pedido deve ter sua data armazenada. 20 | 1. Um pedido aceitará novos itens até que seja fechado. 21 | 1. O relatório de um pedido deve mostrar a descrição de cada uma das pizzas, detalhadamente, e o valor total do pedido. 22 | 23 | ## Versão 0.3 - Pedidos para entrega 24 | 25 | A pizzaria quer ampliar seus negócios realizando _pedidos para entrega_ de pizzas. 26 | 27 | - Um **pedido local** continua com as regras atuais, porém passando a cobrar uma taxa de `10%` de serviço para os atendentes. 28 | - Um **pedido para entrega** tem um limite de `6` pizzas. Ele não tem taxa de serviço, mas sim taxa de entrega de acordo com a distância: 29 | - Até `4km`: isento. 30 | - De `4,01` até `8km`: `R$5` 31 | - Acima de `8km`: `R$8` 32 | 33 | ## Versão 0.3b - Sanduíches e Pizzas 34 | 35 | A Xulambs Pizza está progredindo rapidamente nos seus negócios locais e para entrega. Agora, querem diversificar seu público oferecendo outras opções de comidas. O primeiro passo nessa direção é a inclusão de _sanduíches_ no cardápio. 36 | 37 | Os sanduíches seguem um modelo de venda similar ao que está dando certo para as pizzas: 38 | - Preço inicial de `R$15`; 39 | - Podem receber até `5` adicionais, custando `R$3` cada; 40 | - Podem fazer parte de um _combo com fritas_ e, neste caso, há um acréscimo de `R$5`. 41 | 42 | Para incentivar a venda de pizzas, que são mais caras, os gestores decidiram criar uma nova regra de preço: a partir do `6° adicional` da pizza, eles terão `50%` de desconto. 43 | -------------------------------------------------------------------------------- /Código/XulambsFoods/src/PedidoLocal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace XulambsFoods_2024_2.src 8 | { 9 | public class PedidoLocal : IPedido 10 | { 11 | /// 12 | /// Para criar um vetor de pizzas de tamanho grande 13 | /// 14 | private const int MaxPizzas = 100; 15 | private const double TaxaServico = 0.1; 16 | private BaseDados _comidas; 17 | 18 | 19 | public PedidoLocal() 20 | { 21 | _comidas = new BaseDados(); 22 | } 23 | 24 | 25 | public double ValorItens() { 26 | return _comidas.Totalizador(c => c.ValorFinal()); 27 | } 28 | 29 | 30 | public double ValorTaxa() { 31 | return ValorItens() * TaxaServico; 32 | } 33 | 34 | /// 35 | /// Verifica se uma comida pode ser adicionada ao pedido, ou seja, se o pedido está aberto e há espaço na memória. O parâmetro comida não pode ser nulo, ou causará uma exceção. 36 | /// 37 | /// TRUE se puder adicionar, FALSE caso contrário 38 | public int Adicionar(Comida comida) { 39 | _comidas.Add(comida); 40 | return _comidas.Quantidade(); 41 | } 42 | 43 | /// 44 | /// Cria um relatório para o pedido, contendo seu número, sua data(DD/MM/AAAA), detalhamento de cada pizza e o preço final a ser pago. 45 | /// 46 | /// String com os detalhes especificados: 47 | ///
48 | 	    ///PEDIDO - NÚMERO - DD/MM/AAAA
49 | 	    ///01 - DESCRICAO DA PIZZA
50 | 	    ///02 - DESCRICAO DA PIZZA
51 | 	    ///03 - DESCRICAO DA PIZZA
52 |         ///
53 | 	    ///TOTAL A PAGAR: R$ VALOR
54 | 	    ///
55 | public string Relatorio() { 56 | StringBuilder sb = new StringBuilder(" - LOCAL\n"); 57 | sb.AppendLine("============================="); 58 | 59 | sb.AppendLine(_comidas.RelatorioOrdenado()); 60 | 61 | sb.AppendLine($"TAXA SERVIÇO : {ValorTaxa():C2}"); 62 | return sb.ToString(); 63 | } 64 | 65 | public override string ToString() { 66 | return $"Pedido Local com valor de {(ValorItens() + ValorTaxa()):C2}"; 67 | } 68 | 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | 9 | # Build results 10 | 11 | [Dd]ebug/ 12 | [Rr]elease/ 13 | x64/ 14 | [Bb]in/ 15 | [Oo]bj/ 16 | 17 | .vs/ 18 | 19 | # MSTest test Results 20 | [Tt]est[Rr]esult*/ 21 | [Bb]uild[Ll]og.* 22 | 23 | *_i.c 24 | *_p.c 25 | *_i.h 26 | *.ilk 27 | *.meta 28 | *.obj 29 | *.pch 30 | *.pdb 31 | *.pgc 32 | *.pgd 33 | *.rsp 34 | *.sbr 35 | *.tlb 36 | *.tli 37 | *.tlh 38 | *.tmp 39 | *.tmp_proj 40 | *.log 41 | *.vspscc 42 | *.vssscc 43 | .builds 44 | *.pidb 45 | *.log 46 | *.svclog 47 | *.scc 48 | 49 | # Visual C++ cache files 50 | ipch/ 51 | *.aps 52 | *.ncb 53 | *.opensdf 54 | *.sdf 55 | *.cachefile 56 | 57 | # Visual Studio profiler 58 | *.psess 59 | *.vsp 60 | *.vspx 61 | *.vsidx 62 | 63 | # Guidance Automation Toolkit 64 | *.gpState 65 | 66 | # ReSharper is a .NET coding add-in 67 | _ReSharper*/ 68 | *.[Rr]e[Ss]harper 69 | *.DotSettings.user 70 | 71 | # Click-Once directory 72 | publish/ 73 | 74 | # Publish Web Output 75 | *.Publish.xml 76 | *.pubxml 77 | *.azurePubxml 78 | 79 | # NuGet Packages Directory 80 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line 81 | packages/ 82 | ## TODO: If the tool you use requires repositories.config, also uncomment the next line 83 | !packages/repositories.config 84 | 85 | # Windows Azure Build Output 86 | csx/ 87 | *.build.csdef 88 | 89 | # Windows Store app package directory 90 | AppPackages/ 91 | 92 | # Others 93 | sql/ 94 | *.Cache 95 | ClientBin/ 96 | [Ss]tyle[Cc]op.* 97 | ![Ss]tyle[Cc]op.targets 98 | ~$* 99 | *~ 100 | *.dbmdl 101 | *.[Pp]ublish.xml 102 | 103 | *.publishsettings 104 | 105 | # RIA/Silverlight projects 106 | Generated_Code/ 107 | 108 | # Backup & report files from converting an old project file to a newer 109 | # Visual Studio version. Backup files are not needed, because we have git ;-) 110 | _UpgradeReport_Files/ 111 | Backup*/ 112 | UpgradeLog*.XML 113 | UpgradeLog*.htm 114 | 115 | # SQL Server files 116 | App_Data/*.mdf 117 | App_Data/*.ldf 118 | 119 | # ========================= 120 | # Windows detritus 121 | # ========================= 122 | 123 | # Windows image file caches 124 | Thumbs.db 125 | ehthumbs.db 126 | 127 | # Folder config file 128 | Desktop.ini 129 | 130 | # Recycle Bin used on file shares 131 | $RECYCLE.BIN/ 132 | 133 | # Mac desktop service store files 134 | .DS_Store 135 | 136 | _NCrunch* 137 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/00_HerancaPessoa/Professor.cs: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2025 João Caram 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | namespace HerancaPessoa 25 | { 26 | public class Professor : Pessoa 27 | { 28 | 29 | private static double s_horaAula = 30.35; 30 | 31 | /// 32 | /// Cria um professor com nome, data de nascimento, documento e email. 33 | /// A carga horária padrão é de 20h e pode ser alterada por meio do 34 | /// método herdado de Pessoa. 35 | /// 36 | /// Nome da pessoa 37 | /// Data de nascimento 38 | /// Um documento identificador 39 | /// O email de contato da pessoa 40 | public Professor(string nome, DateOnly nascimento, string documento, string email) : 41 | base(nome, nascimento, documento, email) 42 | { 43 | _cargaHoraria = 20; 44 | } 45 | 46 | /// 47 | /// Salário bruto do professor, que inclui 20% de extra classe. 48 | /// 49 | /// Double positivo com o valor do salário bruto do professor. 50 | public double SalarioBruto() 51 | { 52 | return s_horaAula * (_cargaHoraria*4.5) * 1.20; 53 | } 54 | 55 | /// 56 | /// Resumo do professor: nome, idade (vindo da classe mãe) e salário bruto. 57 | /// 58 | /// String de uma linha com as informações acima 59 | public override string Relatorio() 60 | { 61 | return $"{base.Relatorio()} Salário {SalarioBruto():C2}."; 62 | } 63 | 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Código/00_Revisao/Produtos/Produto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | /** 8 | * MIT License 9 | * 10 | * Copyright(c) 2024 João Caram 11 | * 12 | * Permission is hereby granted, free of charge, to any person obtaining a copy 13 | * of this software and associated documentation files (the "Software"), to deal 14 | * in the Software without restriction, including without limitation the rights 15 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 16 | * copies of the Software, and to permit persons to whom the Software is 17 | * furnished to do so, subject to the following conditions: 18 | * 19 | * The above copyright notice and this permission notice shall be included in all 20 | * copies or substantial portions of the Software. 21 | * 22 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 23 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 24 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 25 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 26 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 27 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 28 | * SOFTWARE. 29 | */ 30 | 31 | /* 32 | * Classe Produto simples para demonstração de atributos e métodos 33 | */ 34 | 35 | namespace Produtos { 36 | internal class Produto { 37 | 38 | /// 39 | /// Descrição do produto 40 | /// 41 | public string descricao; 42 | /// 43 | /// Preço de venda de uma unidade 44 | /// 45 | public float precoUnitario; 46 | 47 | /// 48 | /// Informa o preço de venda de um lote do produto com 'quantidade' unidades. 49 | /// Se a quantidade passada for negativa, retorna 0. 50 | /// 51 | /// Tamanho do lote a ser vendido 52 | /// Preço do lote com a 'quantidade' de produtos, ou 0 em caso de quantidade negativa (float) 53 | public float precoPorLote(int quantidade) { 54 | float valor = 0f; 55 | if(quantidade>0) 56 | valor = precoUnitario * quantidade; 57 | return valor; 58 | } 59 | 60 | /// 61 | /// Retorna uma string formatada com a descrição e o preço unitário do produto. 62 | /// Inclui o símbolo de R$ e preço formatado com 2 casas decimais. 63 | /// 64 | /// Descrição do produto e seu preço com duas casas decimais (string) 65 | public string descricaoProduto() { 66 | return descricao + " - Preço Unitário: R$ " + precoUnitario.ToString("0.00"); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Código/XulambsFoods/src/Sanduiche.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | 4 | /** 5 | * MIT License 6 | * 7 | * Copyright(c) 2024 João Caram 8 | * 9 | * Permission is hereby granted, free of charge, to any person obtaining a copy 10 | * of this software and associated documentation files (the "Software"), to deal 11 | * in the Software without restriction, including without limitation the rights 12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | * copies of the Software, and to permit persons to whom the Software is 14 | * furnished to do so, subject to the following conditions: 15 | * 16 | * The above copyright notice and this permission notice shall be included in all 17 | * copies or substantial portions of the Software. 18 | * 19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 25 | * SOFTWARE. 26 | */ 27 | 28 | namespace XulambsFoods_2024_2.src { 29 | public class Sanduiche : Comida { 30 | private const int MaxIngredientes = 5; 31 | private const string Descricao = "Sanduiche"; 32 | private const double PrecoBase = 15d; 33 | private const double ValorAdicional = 3d; 34 | private const double ValorCombo = 5; 35 | private bool _comboFritas; 36 | 37 | public Sanduiche() : base(Descricao, MaxIngredientes, PrecoBase, ValorAdicional) { 38 | _comboFritas = false; 39 | } 40 | 41 | public Sanduiche(int quantosAdicionais) : 42 | base(Descricao, MaxIngredientes, PrecoBase, ValorAdicional) 43 | { 44 | _comboFritas = false; 45 | AdicionarIngredientes(quantosAdicionais); 46 | } 47 | 48 | public Sanduiche(bool combo) : 49 | base(Descricao, MaxIngredientes, PrecoBase, ValorAdicional) 50 | { 51 | _comboFritas = combo; 52 | } 53 | 54 | public Sanduiche(int quantosAdicionais, bool combo) : 55 | base(Descricao, MaxIngredientes, PrecoBase, ValorAdicional) 56 | { 57 | _comboFritas = combo; 58 | AdicionarIngredientes(quantosAdicionais); 59 | } 60 | 61 | public override double ValorFinal() { 62 | double valorInicial = PrecoBase + ValorAdicionais(); 63 | return (_comboFritas) ? valorInicial + ValorCombo: valorInicial; 64 | } 65 | 66 | public override string NotaDeCompra() { 67 | string notinha = base.NotaDeCompra(); 68 | if(_comboFritas) 69 | notinha += $"\n\tCombo com fritas: {ValorCombo:C2}"; 70 | notinha += $"\nVALOR A PAGAR: {ValorFinal():C2}"; 71 | return notinha; 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/00_HerancaPessoa/Aluno.cs: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2025 João Caram 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | namespace HerancaPessoa 25 | { 26 | public class Aluno : Pessoa 27 | { 28 | 29 | 30 | private static double s_horaAula; 31 | private double _valorMatricula; 32 | 33 | static Aluno() 34 | { 35 | s_horaAula = 25d; 36 | } 37 | 38 | /// 39 | /// Construtor de um aluno, que recebe nome, data de nascimento, 40 | /// documento e um email de contato. O aluno também recebe o valor 41 | /// pago como matrícula (mínimo de R$1000) 42 | /// 43 | /// Nome da pessoa 44 | /// Data de nascimento 45 | /// Um documento identificador 46 | /// O email de contato da pessoa 47 | /// Matrícula paga (>=1000) 48 | public Aluno(string nome, DateOnly nascimento, string documento, string email, 49 | double valorMatricula) : 50 | base(nome, nascimento, documento, email) 51 | { 52 | if (valorMatricula < 1000d) 53 | valorMatricula = 1000d; 54 | _valorMatricula = valorMatricula; 55 | } 56 | 57 | /// 58 | /// Valor da mensalidade do aluno: sua carga horária total do semestre, 59 | /// multiplicado pelo valor da hora aula, descontando-se o valor pago 60 | /// como matrícula - e tudo isso dividido por 6 meses. 61 | /// 62 | /// Double com o valor da mensalidade 63 | public double ValorMensalidade() 64 | { 65 | return ((_cargaHoraria * s_horaAula) - _valorMatricula) / 6.0; 66 | } 67 | 68 | public override string Relatorio() 69 | { 70 | return $"{_nome} ({_id}) - Carga horária de {_cargaHoraria}h no semestre. Mensalidade: {ValorMensalidade():C2}"; 71 | } 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /Código/XulambsFoods/src/Comida.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | 4 | /** 5 | * MIT License 6 | * 7 | * Copyright(c) 2024 João Caram 8 | * 9 | * Permission is hereby granted, free of charge, to any person obtaining a copy 10 | * of this software and associated documentation files (the "Software"), to deal 11 | * in the Software without restriction, including without limitation the rights 12 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | * copies of the Software, and to permit persons to whom the Software is 14 | * furnished to do so, subject to the following conditions: 15 | * 16 | * The above copyright notice and this permission notice shall be included in all 17 | * copies or substantial portions of the Software. 18 | * 19 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 25 | * SOFTWARE. 26 | */ 27 | 28 | namespace XulambsFoods_2024_2.src { 29 | public abstract class Comida : IComparable { 30 | private int _maxIngredientes; 31 | private string _descricao; 32 | private double _precoBase; 33 | private double _valorAdicional; 34 | protected int _quantidadeIngredientes; 35 | 36 | protected Comida(string desc, int maxAdicionais, double valorBase, double valorAdicional) { 37 | _descricao = desc; 38 | _maxIngredientes = maxAdicionais; 39 | _precoBase = valorBase; 40 | _valorAdicional = valorAdicional; 41 | _quantidadeIngredientes = 0; 42 | } 43 | 44 | /// 45 | /// Calcula o valor dos adicionais para o preço final da pizza. Atualmente o valor dos adicionais é a multiplicação da quantidade de adicionais por seu valor unitário 46 | /// 47 | /// Double com o valor a ser cobrado pelos adicionais. 48 | protected double ValorAdicionais() { 49 | return _quantidadeIngredientes * _valorAdicional; 50 | } 51 | 52 | /// 53 | ///Faz a verificação de limites para adicionar ingredientes na pizza.Retorna TRUE/FALSE conforme seja possível ou não adicionar 54 | ///esta quantidade de ingredientes. 55 | /// 56 | /// Quantidade de ingredientes a adicionar. 57 | /// TRUE/FALSE conforme seja possível ou não adicionar esta quantidade de ingredientes. 58 | protected bool PodeAdicionar(int quantos) { 59 | return (quantos > 0 && quantos + _quantidadeIngredientes <= _maxIngredientes); 60 | } 61 | 62 | public abstract double ValorFinal(); 63 | 64 | /// 65 | /// Tenta adicionar ingredientes na pizza.Caso a adição seja inválida(ultrapassando limites ou com valores negativos), mantém 66 | /// a quantidade atual de ingredientes.Retorna a quantidade de ingredientes após a execução do método. 67 | /// 68 | /// Quantos ingredientes a serem adicionados (>0) 69 | /// Quantos ingredientes a pizza tem após a execução 70 | public int AdicionarIngredientes(int quantos) { 71 | if (PodeAdicionar(quantos)) { 72 | _quantidadeIngredientes += quantos; 73 | } 74 | return _quantidadeIngredientes; 75 | } 76 | 77 | public virtual string NotaDeCompra() { 78 | return $"{_descricao} ({_precoBase:C2}) com {_quantidadeIngredientes} ingredientes ({ValorAdicionais():C2})."; 79 | } 80 | 81 | public override string ToString() { 82 | return NotaDeCompra(); 83 | } 84 | public int CompareTo(object? obj) 85 | { 86 | Comida outra = (Comida)obj; 87 | int comparacaoDescricao = _descricao.CompareTo(outra._descricao); 88 | return (comparacaoDescricao == 0) ? _quantidadeIngredientes.CompareTo(outra._quantidadeIngredientes) : comparacaoDescricao; 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /Código/02_Polimorfismo/00_HerancaPessoa/Pessoa.cs: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2025 João Caram 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | namespace HerancaPessoa 26 | { 27 | /// 28 | /// Demonstração básica dos conceitos do polimorfismo universal de inclusão: 29 | ///
    30 | ///
  • Acoplamento com o construtor da classe mãe
  • 31 | ///
  • Herança de membros protegidos e públicos
  • 32 | ///
  • Métodos virtuais e sobrescritos
  • 33 | ///
  • Uso de "base" no reúso de código
  • 34 | ///
35 | ///
36 | public class Pessoa 37 | { 38 | private static Random s_sorteio = new Random(42); 39 | protected int _id; 40 | protected string _nome; 41 | protected string _documento; 42 | protected DateOnly _dataNasc; 43 | protected string _email; 44 | protected int _cargaHoraria; 45 | 46 | /// 47 | /// Cria uma pessoa com nome, data de nascimento, documento e email. 48 | /// Como trata-se de uma demonstração, sem requisitos envolvidos, 49 | /// nenhum dado é validado. 50 | /// 51 | /// Nome da pessoa 52 | /// Data de nascimento 53 | /// Um documento identificador 54 | /// O email de contato da pessoa 55 | public Pessoa(string nome, DateOnly nascimento, string documento, string email) 56 | { 57 | _nome = nome; 58 | _dataNasc = nascimento; 59 | _documento = documento; 60 | _id = s_sorteio.Next() % 1_000_000; 61 | _email = email; 62 | } 63 | 64 | /// 65 | /// Aloca uma carga horária para a pessoa no âmbito da Universidade. 66 | /// A carga precisa ser maior que 0. 67 | /// 68 | /// Valor da carga horária atual (> 0) 69 | public void SetCargaHoraria(int cargaHoraria) 70 | { 71 | if (cargaHoraria > 0) 72 | _cargaHoraria = cargaHoraria; 73 | } 74 | 75 | 76 | /// 77 | /// Retorna a idade da pessoa. 78 | /// 79 | /// Int com a idade da pessoa (valor não negativo) 80 | public int Idade() 81 | { 82 | DateOnly hoje = DateOnly.FromDateTime(DateTime.Now); 83 | int idade = (hoje.Year - _dataNasc.Year); 84 | if (hoje.DayOfYear > _dataNasc.DayOfYear) 85 | idade--; 86 | return idade; 87 | } 88 | 89 | /// 90 | /// Stub para simular o envio de um email 91 | /// 92 | /// 93 | public void EnviarEmail(string texto) 94 | { 95 | //fingindo que estou usando um serviço bacanudo para enviar emails 96 | } 97 | 98 | /// 99 | /// Cria uma string com nome e idade da pessoa. 100 | /// 101 | /// String com nome e idade (em anos) da pessoa 102 | public virtual string Relatorio() 103 | { 104 | return $"{_nome}: {Idade()} anos."; 105 | } 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /Código/XulambsFoods/src/Pizza.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Net; 7 | using System.Runtime.Intrinsics.X86; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using static System.Net.Mime.MediaTypeNames; 11 | using static System.Net.WebRequestMethods; 12 | using static System.Runtime.InteropServices.JavaScript.JSType; 13 | 14 | namespace XulambsFoods_2024_2.src { 15 | /** 16 | * MIT License 17 | * 18 | * Copyright(c) 2024 João Caram 19 | * 20 | * Permission is hereby granted, free of charge, to any person obtaining a copy 21 | * of this software and associated documentation files (the "Software"), to deal 22 | * in the Software without restriction, including without limitation the rights 23 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 24 | * copies of the Software, and to permit persons to whom the Software is 25 | * furnished to do so, subject to the following conditions: 26 | * 27 | * The above copyright notice and this permission notice shall be included in all 28 | * copies or substantial portions of the Software. 29 | * 30 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 31 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 32 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 33 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 34 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 35 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 36 | * SOFTWARE. 37 | */ 38 | 39 | /// 40 | /// Classe Pizza para a Xulambs Pizza. Uma pizza tem um preço base e pode ter até 8 ingredientes adicionais. Cada ingrediente tem custo fixo. 41 | /// A pizza deve emitir uma nota de compra com os seus detalhes. 42 | /// 43 | public class Pizza : Comida{ 44 | 45 | private const int MaxIngredientes = 8; 46 | private const string Descricao = "Pizza"; 47 | private const double PrecoBase = 29d; 48 | private const double ValorAdicional = 5d; 49 | private const int AdicionaisParaDesconto = 5; 50 | private const double PctDesconto = 0.5; 51 | 52 | 53 | /// 54 | /// Construtor padrão.Cria uma pizza sem adicionais. 55 | /// 56 | public Pizza() : base(Descricao, MaxIngredientes, PrecoBase, ValorAdicional) 57 | { 58 | } 59 | 60 | /// 61 | /// Cria uma pizza com a quantidade de adicionais pré-definida.Em caso de valor inválido, a pizza será criada sem adicionais. 62 | /// 63 | /// Quantidade de adicionais (entre 0 e 8, limites inclusivos) 64 | public Pizza(int quantosAdicionais) : 65 | base(Descricao, MaxIngredientes, PrecoBase, ValorAdicional) 66 | { 67 | AdicionarIngredientes(quantosAdicionais); 68 | } 69 | 70 | private double DescontoAdicionais() { 71 | double desconto = 0d; 72 | int quantosTemDesconto = _quantidadeIngredientes - AdicionaisParaDesconto; 73 | if(quantosTemDesconto > 0) { 74 | desconto = quantosTemDesconto * ValorAdicional * PctDesconto; 75 | } 76 | return desconto; 77 | } 78 | 79 | /// 80 | /// Retorna o valor final da pizza, incluindo seus adicionais e descontos. 81 | /// 82 | /// Double com o valor final da pizza. 83 | public override double ValorFinal() { 84 | return PrecoBase + ValorAdicionais() - DescontoAdicionais(); 85 | } 86 | 87 | 88 | /// 89 | /// Nota simplificada de compra: descrição da pizza, dos ingredientes e do preço. 90 | /// 91 | /// String no formato " com ingredientes , no valor total de " 92 | public override string NotaDeCompra() { 93 | string notinha = base.NotaDeCompra(); 94 | notinha += $"\n\tDesconto: {DescontoAdicionais():C2}\n"; 95 | notinha += $"VALOR A PAGAR: {ValorFinal():C2}"; 96 | return notinha; 97 | } 98 | 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /Código/01_Basicos/Produto/Produto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | /** 8 | * MIT License 9 | * 10 | * Copyright(c) 2024 João Caram 11 | * 12 | * Permission is hereby granted, free of charge, to any person obtaining a copy 13 | * of this software and associated documentation files (the "Software"), to deal 14 | * in the Software without restriction, including without limitation the rights 15 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 16 | * copies of the Software, and to permit persons to whom the Software is 17 | * furnished to do so, subject to the following conditions: 18 | * 19 | * The above copyright notice and this permission notice shall be included in all 20 | * copies or substantial portions of the Software. 21 | * 22 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 23 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 24 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 25 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 26 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 27 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 28 | * SOFTWARE. 29 | */ 30 | 31 | namespace Comercio { 32 | internal class Produto { 33 | /// 34 | /// Descrição do produto a ser vendido 35 | /// 36 | private string _descricao; 37 | 38 | /// 39 | /// Valor de uma unidade do produto. O valor mínimo é 1. 40 | /// 41 | private double _valorUnitario; 42 | 43 | /// 44 | /// Variável de acesso para o valor unitário. Retorna o valor e faz a mudança do valor 45 | /// considerando a validação de preço mínimo. 46 | /// 47 | public double valorUnitario { 48 | get => _valorUnitario; 49 | set => validarValor(value); 50 | } 51 | 52 | /// 53 | /// Reajusta o preço de um produto. O valor deve ser acima do mínimo (R$1). 54 | /// Valores abaixo do mínimo serão ignorados. 55 | /// 56 | /// Novo valor unitário do produto. Deve ser no mínimo R$1 57 | public void reajustar(double valor) { 58 | validarValor(valor); 59 | } 60 | 61 | /// 62 | /// Método privado para encapsular a validação de valor unitário. Se o valor for 63 | /// abaixo do mínimo, a ação é ignorada. 64 | /// 65 | /// Novo valor unitário para o produto, com mínimo de R$1 66 | private void validarValor(double valor) { 67 | _valorUnitario = 1.0; 68 | if (valor > 1) 69 | _valorUnitario = valor; 70 | } 71 | 72 | 73 | /// 74 | /// Registra dados de um produto, sendo estes a descrição (mínimo 2 caracteres) 75 | /// e preço unitário (mínimo R$1). 76 | /// Em caso de erro, a descrição será "Sem descrição" e o preço fica como R$1. 77 | /// 78 | /// A descrição do produto (mínimo 2 caracteres) 79 | /// O preço unitário (mínimo R$ 1) 80 | public void registrar(string desc, double valor) { 81 | if (desc.Length >= 2) 82 | _descricao = desc; 83 | else 84 | _descricao = "Sem descrição"; 85 | validarValor(valor); 86 | } 87 | 88 | /// 89 | /// Calcula o valor de venda de um lote do produto a partir de uma quantidade passada por parâmetro. 90 | /// Em caso de quantidade menor que 1, retorna sempre 0. 91 | /// 92 | /// Quantidade de produtos do lote (mínimo: 1) 93 | /// Double com o valor de venda do lote com a quantidade especificada ou 0 em caso de problemas 94 | public double valorLote(int quant) { 95 | double valor = 0.0; 96 | if(quant>0) 97 | valor = quant * _valorUnitario; 98 | return valor; 99 | } 100 | 101 | /// 102 | /// Retorna os dados do Produto em string (a ser melhorado com polimorfismo futuramente). 103 | /// Os dados incluem descrição e o valor unitário com duas casas decimais. 104 | /// 105 | /// String com descrição e o valor unitário com duas casas decimais. 106 | public override string ToString() { 107 | return $"{_descricao} - valor unitário: {_valorUnitario:C2}"; 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /Código/XulambsFoods/src/Pedido.cs: -------------------------------------------------------------------------------- 1 | using System.Drawing; 2 | using System.Runtime.ConstrainedExecution; 3 | using System.Text; 4 | using static System.Runtime.InteropServices.JavaScript.JSType; 5 | 6 | namespace XulambsFoods_2024_2.src 7 | { 8 | /// 9 | /// Classe Pedido: composição com classe Pizza. Um pedido pode conter diversas pizzas. Elas podem ser adicionadas desde que o pedido esteja aberto.Um pedido tem um identificador único e armazena sua data.Ele deve calcular o preço a ser pago por ele e emitir um relatório detalhando suas pizzas e o valor a pagar. 10 | /// 11 | public class Pedido : IComparable, IEquatable 12 | { 13 | 14 | #region static/const 15 | /// 16 | /// Para gerar o id incremental automático 17 | /// 18 | private static int _ultimoPedido; 19 | #endregion 20 | 21 | #region atributos 22 | private IPedido modalidade; 23 | private int _idPedido; 24 | private DateOnly _data; 25 | 26 | private int _quantComidas; 27 | private bool _aberto; 28 | #endregion 29 | 30 | #region construtores 31 | static Pedido() 32 | { 33 | _ultimoPedido = 0; 34 | } 35 | 36 | /// 37 | /// Cria um pedido com a data de hoje. Identificador é gerado automaticamente a partir do último identificador armazenado. 38 | /// 39 | public Pedido(double distancia) 40 | { 41 | _quantComidas = 0; 42 | _aberto = true; 43 | _data = DateOnly.FromDateTime(DateTime.Now); 44 | _idPedido = ++_ultimoPedido; 45 | setModalidade(distancia); 46 | } 47 | 48 | private void setModalidade(double distancia) { 49 | modalidade = (distancia > 0) ? new PedidoEntrega(distancia) : new PedidoLocal(); 50 | } 51 | #endregion 52 | 53 | #region métodos de negócio 54 | 55 | protected double ValorItens() 56 | { 57 | return modalidade.ValorItens(); 58 | } 59 | 60 | 61 | 62 | /// 63 | /// Adiciona uma comida ao pedido. A comida não pode ser um objeto nulo. 64 | /// 65 | /// Comida a ser adicionada. Não pode ser um objeto nulo 66 | /// 67 | /// ArgumentNullException se a comida for inválida 68 | /// 69 | public int Adicionar(Comida comida) { 70 | if (comida == null) 71 | throw new ArgumentNullException("Comida para o pedido não pode ser vazia."); 72 | if (!_aberto) 73 | throw new InvalidOperationException("Não se pode alterar um pedido fechado."); 74 | 75 | _quantComidas = modalidade.Adicionar(comida); 76 | return _quantComidas; 77 | } 78 | 79 | /// 80 | /// Fecha um pedido, desde que ele contenha pelo menos 1 pizza. Caso esteja vazio, a operação é ignorada. 81 | /// 82 | public void FecharPedido() 83 | { 84 | if (_quantComidas > 0) 85 | _aberto = false; 86 | } 87 | 88 | /// 89 | /// Calcula o preço a ser pago pelo pedido (no momento, a soma dos preços de todas as pizzas contidas no pedido) 90 | /// 91 | /// Double com o valor a ser pago pelo pedido(> 0) 92 | public double PrecoAPagar() 93 | { 94 | return ValorItens() + modalidade.ValorTaxa(); 95 | } 96 | 97 | public string Relatorio() { 98 | StringBuilder relat = new StringBuilder("XULAMBS PIZZA - Pedido "); 99 | relat.Append($"{_idPedido:D2} - {_data.ToShortDateString()}"); 100 | relat.AppendLine(modalidade.Relatorio()); 101 | relat.AppendLine($"TOTAL A PAGAR: {PrecoAPagar():C2}"); 102 | relat.AppendLine("============================="); 103 | return relat.ToString(); 104 | } 105 | 106 | public override string ToString() { 107 | return Relatorio(); 108 | } 109 | 110 | public override bool Equals(object? obj) { 111 | Pedido outro = (Pedido)obj; 112 | return _idPedido == outro._idPedido && _data.Equals(outro._data); 113 | } 114 | 115 | public bool Equals(int other) { 116 | return _idPedido == other; 117 | } 118 | 119 | public override int GetHashCode() { 120 | return _idPedido; 121 | } 122 | 123 | public int CompareTo(object? other) { 124 | Pedido outro = (Pedido)other; 125 | int resposta = 0; 126 | double meuValor = PrecoAPagar(); 127 | double valorDoOutro = outro.PrecoAPagar(); 128 | 129 | double diferenca = meuValor - valorDoOutro; 130 | 131 | if(diferenca < 0) { 132 | resposta = -1; 133 | } 134 | else if(diferenca > 0) { 135 | resposta = 1; 136 | } 137 | return resposta; 138 | } 139 | #endregion 140 | } 141 | } -------------------------------------------------------------------------------- /Código/02_Polimorfismo/01_Polimorfismo_Formas/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace PoliFiguras { 4 | internal class Program { 5 | static Random aleatorio = new Random(42); 6 | 7 | static int MenuPrincipal() { 8 | string linha = "========================="; 9 | //TODO: refatorar menu 10 | Console.Clear(); 11 | Console.WriteLine("FORMAS E MAIS FORMAS"); 12 | Console.WriteLine(linha); 13 | Console.WriteLine("CRIAR / LISTAR / LOCALIZAR"); 14 | Console.WriteLine("1 - Criar novo conjunto"); 15 | Console.WriteLine("2 - Adicionar forma fixa"); 16 | Console.WriteLine("3 - Listar todas as formas"); 17 | Console.WriteLine("4 - Pegar/Localizar um elemento"); 18 | Console.WriteLine("5 - Maior área"); 19 | Console.WriteLine(linha); 20 | Console.WriteLine("0 - Sair"); 21 | Console.Write("\nSua opção: "); 22 | return int.Parse(Console.ReadLine()); 23 | } 24 | 25 | static FormaGeometrica GerarForma() { 26 | int tipo = aleatorio.Next(1, 5); 27 | double dimensao1 = Math.Round((2 + aleatorio.NextDouble() * 7.9),2); 28 | double dimensao2 = Math.Round((2 + aleatorio.NextDouble() * 7.9), 2); 29 | int posX = 1 + aleatorio.Next(80); 30 | int posY = 1 + aleatorio.Next(80); 31 | return tipo switch { 32 | 1 => new Circulo(dimensao1, posX, posY), 33 | 2 => new Retangulo(dimensao1, dimensao2, posX, posY), 34 | 3 => new TrianguloRetangulo(dimensao1, dimensao2, posX, posY), 35 | 4 or _ => new Quadrado(dimensao1, posX, posY) 36 | }; 37 | } 38 | 39 | static ConjuntoGeometrico GerarConjunto() { 40 | Console.Write("Quantas formas geométricas você quer gerar? "); 41 | int quantas = int.Parse(Console.ReadLine()); 42 | if (quantas < 1) 43 | quantas = 1; 44 | ConjuntoGeometrico formas = new ConjuntoGeometrico(quantas+5); 45 | for (int i = 0; i < quantas; i++) { 46 | FormaGeometrica novaForma = GerarForma(); 47 | formas.AddForma(novaForma); 48 | } 49 | return formas; 50 | 51 | } 52 | 53 | 54 | static void AdicionarFormaFixa(ConjuntoGeometrico conjunto) { 55 | if (conjunto == null) 56 | conjunto = GerarConjunto(); 57 | FormaGeometrica quadradinhoDe8 = new Quadrado(8, 42, 24); 58 | conjunto.AddForma(quadradinhoDe8); 59 | } 60 | 61 | static void Relatorio(ConjuntoGeometrico conjunto) { 62 | Console.Clear(); 63 | Console.WriteLine($"Conjunto das formas geométricas: {conjunto.ToString()}"); 64 | } 65 | 66 | static void LocalizarElemento(ConjuntoGeometrico conjunto) { 67 | Console.Clear(); 68 | Console.WriteLine("1 - Círculo"); 69 | Console.WriteLine("2 - Quadrado"); 70 | Console.WriteLine("3 - Retângulo"); 71 | Console.WriteLine("4 - Triângulo Retângulo"); 72 | Console.Write("Escolha a forma: "); 73 | int forma = int.Parse(Console.ReadLine()); 74 | Console.Write("Qual a primeira dimensão? "); 75 | double dimensao1 = double.Parse(Console.ReadLine()); 76 | double dimensao2 = 0d; 77 | if(forma > 2) { 78 | Console.Write("Qual a segunda dimensão? "); 79 | dimensao2 = double.Parse(Console.ReadLine()); 80 | } 81 | 82 | FormaGeometrica f = forma switch { 83 | 1 => new Circulo(dimensao1, 1, 1), 84 | 2 => new Quadrado(dimensao1, 1, 1), 85 | 3 => new Retangulo(dimensao1, dimensao2, 1, 1), 86 | 4 or _ => new TrianguloRetangulo(dimensao1, dimensao2, 1, 1) 87 | }; 88 | 89 | FormaGeometrica procurada = conjunto.Buscar(f); 90 | 91 | if (procurada != null) 92 | Console.WriteLine($"Achei {procurada}"); 93 | else 94 | Console.WriteLine($"Sem forma com estas características: {f}."); 95 | } 96 | 97 | 98 | 99 | 100 | 101 | 102 | static void Main(string[] args) { 103 | 104 | int opcao = MenuPrincipal(); 105 | ConjuntoGeometrico formas = null; 106 | 107 | while (opcao != 0) { 108 | switch (opcao) { 109 | case 1: 110 | formas = GerarConjunto(); 111 | break; 112 | case 2: 113 | AdicionarFormaFixa(formas); 114 | break; 115 | case 3: 116 | Relatorio(formas); 117 | break; 118 | case 4: 119 | LocalizarElemento(formas); 120 | break; 121 | case 5: 122 | Console.WriteLine($"Maior pela área: {formas.MaiorDeTodas()}"); 123 | break; 124 | 125 | } 126 | Console.WriteLine("Enter para continuar. . ."); 127 | Console.ReadKey(); 128 | opcao = MenuPrincipal(); 129 | 130 | } 131 | } 132 | } 133 | } -------------------------------------------------------------------------------- /Código/00_Revisao/Produtos/Program.cs: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2024 João Caram 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | namespace Produtos { 26 | 27 | /** 28 | * Programa demonstração do uso de uma classe produtos e operações básicas com objetos 29 | * Estrutura de dados: vetor 30 | */ 31 | internal class Program { 32 | 33 | /// 34 | /// Carrega um vetor de produtos a partir da leitura do usuário 35 | /// 36 | /// O vetor a ser lido 37 | static void lerVetorProdutos(Produto[] vet) { 38 | Console.Clear(); 39 | for (int i = 0; i < vet.Length; i++){ 40 | vet[i] = new Produto(); 41 | Console.Write("Qual a descrição do produto "+(i+1)+" ? "); 42 | vet[i].descricao = Console.ReadLine(); 43 | Console.Write("Qual o preço unitário do produto " + (i + 1) + " ? "); 44 | vet[i].precoUnitario = float.Parse(Console.ReadLine()); 45 | } 46 | } 47 | 48 | /// 49 | /// Soma os preços dos produtos de um vetor 50 | /// 51 | /// Vetor com os produtos 52 | /// Soma dos preços dos produtos do vetor (float) 53 | static float somaPrecos(Produto[] vet) { 54 | float soma = 0; 55 | for (int i = 0; i < vet.Length; i++) { 56 | soma += vet[i].precoUnitario; 57 | } 58 | return soma; 59 | } 60 | 61 | /// 62 | /// Média dos preços dos produtos de um vetor 63 | /// 64 | /// O vetor com os produtos 65 | /// A média dos preços unitários dos produtos no vetor (float) 66 | static float mediaPrecos(Produto[] vet) { 67 | float soma = somaPrecos(vet); 68 | return soma / vet.Length; 69 | } 70 | 71 | 72 | /// 73 | /// Localiza um produto por sua descrição em um vetor, ainda sem o conceito de encapsulamento. 74 | /// Retorna o produto localizado (objeto) ou null, se não existir. A busca é case-insensitive (transforma em minúsculas para buscar) 75 | /// 76 | /// Descrição do produto a ser localizado 77 | /// Vetor com os produtos 78 | /// Produto localizado (objeto) ou null se ele não existir. 79 | static Produto localizarProduto(string desc, Produto[] vetor) { 80 | string descMinuscula = desc.ToLower(); 81 | foreach (Produto item in vetor){ 82 | if (item.descricao.ToLower().Equals(descMinuscula)) 83 | return item; 84 | } 85 | return null; 86 | } 87 | 88 | /// 89 | /// Encapsula/modulariza a rotina de consultar um produto no vetor. 90 | /// 91 | /// Vetor com os produtos 92 | static void consultarProduto(Produto[] produtos) { 93 | string descricao; 94 | Console.Write("Qual é o nome do produto a consultar? "); 95 | descricao = Console.ReadLine(); 96 | Produto prod = localizarProduto(descricao, produtos); 97 | if (prod != null) { 98 | Console.WriteLine("PRODUTO LOCALIZADO:"); 99 | Console.WriteLine(prod.descricaoProduto()); 100 | } 101 | else 102 | Console.WriteLine("Produto não encontrado."); 103 | } 104 | static void Main(string[] args) { 105 | const int TAM_VETOR = 3; 106 | float media; 107 | string opcao; 108 | 109 | 110 | Produto[] produtos = new Produto[TAM_VETOR]; 111 | 112 | lerVetorProdutos(produtos); 113 | media = mediaPrecos(produtos); 114 | 115 | Console.WriteLine("A média de preço dos produtos é de R$ " + media.ToString("0.##")); 116 | 117 | Console.Write("Deseja consultar um produto (S/N)? "); 118 | opcao = Console.ReadLine().ToLower(); 119 | 120 | while (opcao.Equals("s")){ 121 | 122 | consultarProduto(produtos); 123 | 124 | Console.Write("Enter para continuar."); 125 | Console.ReadKey(); 126 | Console.Clear(); 127 | 128 | Console.Write("Deseja consultar outro produto (S/N)? "); 129 | opcao = Console.ReadLine().ToLower(); 130 | } 131 | 132 | } 133 | } 134 | } 135 | 136 | -------------------------------------------------------------------------------- /Código/XulambsFoods/src/PedidoXulambs.cs: -------------------------------------------------------------------------------- 1 | using System.Drawing; 2 | using System.Runtime.ConstrainedExecution; 3 | using System.Text; 4 | using static System.Runtime.InteropServices.JavaScript.JSType; 5 | 6 | namespace XulambsFoods_2024_2.src { 7 | /// 8 | /// Classe Pedido: composição com classe Pizza. Um pedido pode conter diversas pizzas. Elas podem ser adicionadas desde que o pedido esteja aberto.Um pedido tem um identificador único e armazena sua data.Ele deve calcular o preço a ser pago por ele e emitir um relatório detalhando suas pizzas e o valor a pagar. 9 | /// 10 | public class PedidoXulambs { 11 | 12 | #region static/const 13 | /// 14 | /// Para gerar o id incremental automático 15 | /// 16 | private static int _ultimoPedido; 17 | /// 18 | /// Para criar um vetor de pizzas de tamanho grande 19 | /// 20 | private const int MaxPizzas = 100; 21 | private const int MaxEntrega = 6; 22 | private const double TaxaServico = 0.1; 23 | private readonly double[] TaxasEntrega = { 0, 5, 8 }; 24 | private readonly double[] DistanciasEntrega= { 4, 8, Double.MaxValue }; 25 | #endregion 26 | 27 | #region atributos 28 | private int _idPedido; 29 | private DateOnly _data; 30 | private Pizza[] _pizzas; 31 | private int _quantPizzas; 32 | private double _distanciaEntrega; 33 | private bool _paraEntrega; 34 | private bool _aberto; 35 | #endregion 36 | 37 | #region construtores 38 | static PedidoXulambs() { 39 | _ultimoPedido = 0; 40 | } 41 | 42 | /// 43 | /// Cria um pedido com a data de hoje. Identificador é gerado automaticamente a partir do último identificador armazenado. 44 | /// 45 | public PedidoXulambs(bool paraEntrega, double distancia) { 46 | _quantPizzas = 0; 47 | _aberto = true; 48 | _pizzas = new Pizza[MaxPizzas]; 49 | _data = DateOnly.FromDateTime(DateTime.Now); 50 | _idPedido = ++_ultimoPedido; 51 | _paraEntrega = paraEntrega; 52 | _distanciaEntrega = distancia; 53 | } 54 | #endregion 55 | 56 | #region métodos de negócio 57 | /// 58 | /// Verifica se uma pizza pode ser adicionada ao pedido, ou seja, se o pedido está aberto e há espaço na memória. 59 | /// 60 | /// TRUE se puder adicionar, FALSE caso contrário 61 | private bool PodeAdicionar() { 62 | bool resposta = _aberto; 63 | if (_paraEntrega) 64 | resposta &= (_quantPizzas < MaxEntrega); 65 | return resposta; 66 | } 67 | 68 | private double ValorTaxa() { 69 | double taxa = ValorItens() * TaxaServico; 70 | if (_paraEntrega) { 71 | for(int i = DistanciasEntrega.Length-1; i>=0; i--) { 72 | if (_distanciaEntrega <= DistanciasEntrega[i]) 73 | taxa = TaxasEntrega[i]; 74 | } 75 | } 76 | return taxa; 77 | } 78 | 79 | private double ValorItens() { 80 | double preco = 0d; 81 | for (int i = 0; i < _quantPizzas; i++) { 82 | preco += _pizzas[i].ValorFinal(); 83 | } 84 | return preco; 85 | } 86 | /// 87 | /// Adiciona uma pizza ao pedido, se for possível. Caso não seja, a operação é ignorada.Retorna a quantidade de pizzas do pedido após a execução. 88 | /// 89 | /// Pizza a ser adicionada 90 | /// A quantidade de pizzas do pedido após a execução. 91 | public int Adicionar(Pizza pizza) { 92 | if (PodeAdicionar()) { 93 | _pizzas[_quantPizzas] = pizza; 94 | _quantPizzas++; 95 | } 96 | return _quantPizzas; 97 | } 98 | 99 | /// 100 | /// Fecha um pedido, desde que ele contenha pelo menos 1 pizza. Caso esteja vazio, a operação é ignorada. 101 | /// 102 | public void FecharPedido() { 103 | if(_quantPizzas > 0) 104 | _aberto = false; 105 | } 106 | 107 | /// 108 | /// Calcula o preço a ser pago pelo pedido (no momento, a soma dos preços de todas as pizzas contidas no pedido) 109 | /// 110 | /// Double com o valor a ser pago pelo pedido(> 0) 111 | public double PrecoAPagar() { 112 | return ValorItens()+ValorTaxa(); 113 | } 114 | 115 | /// 116 | /// Cria um relatório para o pedido, contendo seu número, sua data(DD/MM/AAAA), detalhamento de cada pizza e o preço final a ser pago. 117 | /// 118 | /// String com os detalhes especificados: 119 | ///
120 | 	    ///PEDIDO - NÚMERO - DD/MM/AAAA
121 | 	    ///01 - DESCRICAO DA PIZZA
122 | 	    ///02 - DESCRICAO DA PIZZA
123 | 	    ///03 - DESCRICAO DA PIZZA
124 |         ///
125 | 	    ///TOTAL A PAGAR: R$ VALOR
126 | 	    ///
127 | public string Relatorio() { 128 | StringBuilder relat = new StringBuilder("XULAMBS PIZZA - Pedido "); 129 | relat.Append($"{_idPedido:D2} - {_data.ToShortDateString()}"); 130 | if(_paraEntrega) 131 | relat.AppendLine(" - PARA ENTREGA"); 132 | else 133 | relat.AppendLine(" - LOCAL"); 134 | relat.AppendLine("============================="); 135 | 136 | for (int i = 0; i < _quantPizzas; i++) { 137 | relat.AppendLine($"{(i + 1):D2} - {_pizzas[i].NotaDeCompra()}"); 138 | } 139 | relat.AppendLine($"\nTAXA: {ValorTaxa():C2}"); 140 | relat.AppendLine($"\nTOTAL A PAGAR: {PrecoAPagar():C2}"); 141 | relat.AppendLine("============================="); 142 | return relat.ToString(); 143 | } 144 | #endregion 145 | } 146 | } -------------------------------------------------------------------------------- /Código/01_Basicos/Hora/Hora.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using static System.Runtime.InteropServices.JavaScript.JSType; 7 | 8 | /** 9 | * MIT License 10 | * 11 | * Copyright(c) 2024 João Caram 12 | * 13 | * Permission is hereby granted, free of charge, to any person obtaining a copy 14 | * of this software and associated documentation files (the "Software"), to deal 15 | * in the Software without restriction, including without limitation the rights 16 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 17 | * copies of the Software, and to permit persons to whom the Software is 18 | * furnished to do so, subject to the following conditions: 19 | * 20 | * The above copyright notice and this permission notice shall be included in all 21 | * copies or substantial portions of the Software. 22 | * 23 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 26 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 27 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 28 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 29 | * SOFTWARE. 30 | */ 31 | 32 | 33 | /* 34 | * Classe Hora simples para demonstração de conceitos básicos de POO. 35 | * Primeira fase: atributos, métodos, parâmetros e documentação. 36 | * Há muito a evoluir. 37 | */ 38 | namespace Hora { 39 | internal class Hora { 40 | #region Atributos 41 | /// 42 | /// Representa o componente Hora (entre 0 e 23) 43 | /// 44 | private int horas; 45 | /// 46 | /// Representa o componente Minuto (entre 0 e 59) 47 | /// 48 | private int minutos; 49 | /// 50 | /// Representa o componente Segundo (entre 0 e 59) 51 | /// 52 | private int segundos; 53 | #endregion 54 | 55 | #region Construtores 56 | public Hora(){ 57 | horas = minutos = segundos = 0; 58 | } 59 | 60 | public Hora(int horas, int minutos, int segundos){ 61 | Ajustar(horas, minutos, segundos); 62 | } 63 | #endregion 64 | 65 | #region Métodos de negócio 66 | /// 67 | /// Ajusta o horário com os parâmetros passados pelo usuário. Chama o método de validação e, em caso de não-validação, reverte o horário para 00:00:00 (meia noite) 68 | /// 69 | /// A horas para ser ajustada (0 a 23) 70 | /// O minutos para ser ajustado (0 a 59) 71 | /// O segundos para ser ajustado (0 a 59) 72 | public void Ajustar(int hora, int min, int seg) { 73 | this.horas = hora; 74 | this.minutos = min; 75 | this.segundos = seg; 76 | if (!Validar()) { 77 | this.horas = this.minutos = this.segundos = 0; 78 | } 79 | } 80 | 81 | 82 | /// 83 | /// Faz a validação da horas atribuída. Em caso de horas, minutos ou segundos inválidos, sem reverter o horário em caso de não-validação. 84 | /// 85 | /// TRUE ou FALSE conforme a horas atual é válida ou não 86 | private bool Validar() { 87 | //TODO: revisar o código para melhorá-lo 88 | bool resposta = false; 89 | if ((horas >= 0 && horas <= 23) && 90 | (minutos >= 0 && minutos <= 59) && 91 | (segundos >= 0 && segundos <= 59)) { 92 | resposta = true; 93 | } 94 | return resposta; 95 | } 96 | 97 | /// 98 | /// Incrementa uma quantidade de segundos a uma hora existente, retornando a nova hora. Não modifica a hora já existente. 99 | /// Quantidades menores ou iguais a 0 são ignoradas e é retornada uma hora idêntica à atual. 100 | /// 101 | /// Quantidade de segundos a incrementar (>0) 102 | /// Uma nova hora com os segundos incrementados, podendo ser igual à hora atual em caso de valores não positivos. 103 | public Hora Incrementar(int quantidadeSegundos) { 104 | //TODO: revisar o código para melhorá-lo 105 | int minutosParaSegundos = 60; 106 | int horasParaMinutos = 60; 107 | int horasParaSegundos = minutosParaSegundos * horasParaMinutos; 108 | Hora novaHora = new Hora(); 109 | novaHora.Ajustar(horas, minutos, segundos); 110 | 111 | if (quantidadeSegundos > 0) { 112 | int totalSegundos = (horas * horasParaSegundos + minutos * minutosParaSegundos + segundos) + quantidadeSegundos; 113 | int novosSegundos = totalSegundos % 60; 114 | 115 | int novosMinutos = (totalSegundos / minutosParaSegundos) % horasParaMinutos; 116 | int novasHoras = (totalSegundos / horasParaSegundos) % 24; 117 | 118 | novaHora.Ajustar(novasHoras, novosMinutos, novosSegundos); 119 | } 120 | return novaHora; 121 | } 122 | 123 | public bool EstahNaFrenteDe(Hora outra) { 124 | //TODO: revisar o código para melhorá-lo 125 | int minutosParaSegundos = 60; 126 | int horasParaSegundos = minutosParaSegundos * 60; 127 | 128 | int esta; 129 | esta = (horas * horasParaSegundos + minutos * minutosParaSegundos + segundos); 130 | int aquela; 131 | aquela = outra.horas * horasParaSegundos + outra.minutos * minutosParaSegundos + outra.segundos; 132 | return (esta > aquela); 133 | } 134 | 135 | /// 136 | /// Retorna uma string com a horas formatada como HH:MM:SS. 137 | /// 138 | /// String no formato HH:MM:SS 139 | public string HoraFormatada() { 140 | return $"{horas:D2}:{minutos:D2}:{segundos:D2}"; 141 | } 142 | #endregion 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /Código/XulambsFoods/src/XulambsFoods.cs: -------------------------------------------------------------------------------- 1 | 2 | using System.Reflection.Metadata.Ecma335; 3 | using System.Reflection.PortableExecutable; 4 | using System.Security.Cryptography; 5 | using System.Security.Cryptography.X509Certificates; 6 | 7 | namespace XulambsFoods_2024_2.src { 8 | internal class XulambsFoods { 9 | 10 | static BaseDados todosOsPedidos; 11 | static BaseDados baseClientes; 12 | static List pedidosLista; 13 | static void Cabecalho() { 14 | Console.Clear(); 15 | Console.WriteLine("XULAMBS FOODS"); 16 | Console.WriteLine("============="); 17 | } 18 | 19 | static int lerInteiro(string mensagem) 20 | { 21 | int opcao; 22 | Console.Write($"{mensagem}: "); 23 | try 24 | { 25 | opcao = int.Parse(Console.ReadLine()); 26 | } 27 | catch (FormatException) 28 | { 29 | opcao = -1; 30 | Console.WriteLine("Favor digitar somente números."); 31 | } 32 | catch (OverflowException) { 33 | opcao = -1; 34 | Console.WriteLine("Favor digitar somente valores do menu."); 35 | } 36 | return opcao; 37 | } 38 | static void Pausa() 39 | { 40 | Console.WriteLine("\nDigite ENTER para continuar."); 41 | Console.ReadKey(); 42 | } 43 | static int ExibirMenu() { 44 | Cabecalho(); 45 | Console.WriteLine("1 - Abrir Pedido"); 46 | Console.WriteLine("2 - Alterar Pedido"); 47 | Console.WriteLine("3 - Relatório de Pedido"); 48 | Console.WriteLine("4 - Encerrar Pedido"); 49 | Console.WriteLine("5 - Relatório geral de pedidos"); 50 | Console.WriteLine("6 - Relatório geral de clientes (nome)"); 51 | Console.WriteLine("7 - Relatório geral de clientes (gasto)"); 52 | Console.WriteLine("8 - Total vendido em pedidos"); 53 | Console.WriteLine("0 - Finalizar"); 54 | 55 | return lerInteiro("Digite sua escolha"); 56 | 57 | } 58 | 59 | static Pedido EscolherTipoPedido() { 60 | Pedido novoPedido; 61 | int escolha; 62 | Cabecalho(); 63 | 64 | Console.WriteLine("Abrindo um novo Pedido."); 65 | Console.WriteLine("1 - Pedido Local."); 66 | Console.WriteLine("2 - Pedido para Entrega."); 67 | 68 | escolha = lerInteiro("Escolha um tipo de pedido"); 69 | 70 | novoPedido = escolha switch { 71 | -1 => null, 72 | 2 => CriarPedidoEntrega(), 73 | 1 or _ => new Pedido(0) 74 | }; 75 | 76 | return novoPedido; 77 | 78 | } 79 | 80 | private static Pedido CriarPedidoEntrega() { 81 | double dist; 82 | Console.WriteLine("\nPedido para Entrega."); 83 | Console.Write("Qual a distância da entrega? "); 84 | dist = double.Parse(Console.ReadLine()); 85 | return new Pedido(dist); 86 | } 87 | 88 | static Pedido AbrirPedido() { 89 | Cabecalho(); 90 | Pedido novoPedido = EscolherTipoPedido(); 91 | Console.WriteLine("\n"+novoPedido.Relatorio()); 92 | Pausa(); 93 | AdicionarComidas(novoPedido); 94 | return novoPedido; 95 | } 96 | 97 | private static void AdicionarComidas(Pedido procurado) { 98 | string escolha; 99 | do { 100 | RelatorioPedido(procurado); 101 | Comida novaComida = ComprarComida(); 102 | EscolherIngredientes(novaComida); 103 | MostrarNota(novaComida); 104 | procurado.Adicionar(novaComida); 105 | 106 | Console.Write("\nDeseja outra comida? (s/n) "); 107 | escolha = Console.ReadLine(); 108 | } while (escolha.ToLower().Equals("s")); 109 | } 110 | 111 | private static Comida? ComprarComida() { 112 | Console.WriteLine("Escolha sua opção: "); 113 | Console.WriteLine("1 - Pizza "); 114 | Console.WriteLine("2 - Sanduíche"); 115 | 116 | int escolha = lerInteiro("Opção"); 117 | return escolha switch { 118 | 1 => ComprarPizza(), 119 | 2 => ComprarSanduiche(), 120 | _ => null 121 | }; 122 | } 123 | 124 | static Comida ComprarPizza() { 125 | Console.WriteLine("\nComprando uma nova pizza:"); 126 | return new Pizza(); 127 | 128 | } 129 | 130 | static Comida ComprarSanduiche() { 131 | Console.WriteLine("\nComprando um novo sanduíche:"); 132 | Console.Write("Deseja combo com fritas? (s/n) "); 133 | string escolha = Console.ReadLine(); 134 | bool querCombo = (escolha.ToLower().Equals("s")) ? true : false; 135 | return new Sanduiche(querCombo); 136 | } 137 | 138 | static void EscolherIngredientes(Comida comida) { 139 | 140 | int adicionais = lerInteiro("Quantos adicionais você deseja?") ; 141 | comida.AdicionarIngredientes(adicionais); 142 | } 143 | 144 | static void MostrarNota(Comida comida) { 145 | Console.WriteLine("\n"+comida.NotaDeCompra()); 146 | } 147 | 148 | static void RelatorioPedido(Pedido pedido) 149 | { 150 | Cabecalho(); 151 | Console.WriteLine(pedido.Relatorio() + "\n"); 152 | } 153 | 154 | static Pedido LocalizarPedido(BaseDados pedidos) { 155 | Cabecalho(); 156 | int id; 157 | Console.WriteLine("Localizando um pedido."); 158 | 159 | id = lerInteiro("ID do pedido"); 160 | 161 | return pedidos.Localizar(id); 162 | } 163 | 164 | static Cliente LocalizarCliente(BaseDados clientes) { 165 | Cabecalho(); 166 | int id; 167 | 168 | id = lerInteiro("ID do Cliente"); 169 | 170 | return clientes.Localizar(id); 171 | } 172 | 173 | static void config() { 174 | gerarClientes(); 175 | gerarPedidos(); 176 | } 177 | 178 | private static void gerarClientes() { 179 | string[] nomes = File.ReadAllLines("medalhistas.txt"); ; 180 | foreach (string nome in nomes) { 181 | Cliente cliente = new Cliente(nome); 182 | baseClientes.Add(cliente); 183 | 184 | } 185 | } 186 | 187 | private static void gerarPedidos() { 188 | Random aleat = new Random(42); 189 | int quantos = baseClientes.Quantidade() * 13; 190 | for (int i = 0; i < quantos; i++) 191 | { 192 | Pedido novoPedido; 193 | int tipoPedido = aleat.Next(100)%2; 194 | 195 | novoPedido = tipoPedido switch { 196 | 0 => new Pedido(0), 197 | 1 => new Pedido(aleat.NextDouble() * 12), 198 | }; 199 | int quantasComidas = aleat.Next(1, 3); 200 | for (int j = 0; j < quantasComidas; j++) 201 | { 202 | Comida novaComida; 203 | int tipoComida = aleat.Next(1, 4); 204 | int ingredientes = aleat.Next(6); 205 | novaComida = tipoComida switch { 206 | 1 => new Pizza(ingredientes), 207 | 2 => new Sanduiche(ingredientes, true), 208 | 3 => new Sanduiche(ingredientes, false) 209 | }; 210 | try 211 | { 212 | novoPedido.Adicionar(novaComida); 213 | } catch(ArgumentNullException anex) 214 | { 215 | Console.WriteLine(anex.Message); 216 | } 217 | } 218 | 219 | novoPedido.FecharPedido(); 220 | int id = aleat.Next(1, baseClientes.Quantidade()+1); 221 | todosOsPedidos.Add(novoPedido); 222 | Cliente cliente = baseClientes.Localizar(id); 223 | cliente.RegistrarPedido(novoPedido); 224 | } 225 | } 226 | 227 | static void Main(string[] args) { 228 | 229 | todosOsPedidos = new BaseDados(); 230 | baseClientes = new BaseDados(); 231 | config(); 232 | 233 | Pedido pedido = null; 234 | Cliente cliente; 235 | int opcao = -1; 236 | do { 237 | opcao = ExibirMenu(); 238 | switch (opcao) { 239 | case 1: 240 | try { 241 | pedido = AbrirPedido(); 242 | todosOsPedidos.Add(pedido); 243 | RelatorioPedido(pedido); 244 | Cliente quem = LocalizarCliente(baseClientes); 245 | string mensagem = "Cliente não existente. Pedido registrado como anônimo."; 246 | if (quem != null) { 247 | quem.RegistrarPedido(pedido); 248 | mensagem = $"Pedido registrado para {quem}"; 249 | } 250 | Console.WriteLine(mensagem); 251 | } 252 | catch (ArgumentNullException ae) { 253 | Console.WriteLine(ae.Message); 254 | } 255 | catch (InvalidOperationException ae) { 256 | Console.WriteLine(ae.Message); 257 | } 258 | catch (NullReferenceException ex) { 259 | Console.WriteLine("Opção inválida. Pedido não foi criado."); 260 | } 261 | 262 | //pedido = AbrirPedido(); 263 | //todosOsPedidos.Add(pedido); 264 | //RelatorioPedido(pedido); 265 | //Cliente quem = LocalizarCliente(todosOsClientes); 266 | //String mensagem = "Cliente não existente. Pedido registrado como anônimo"; 267 | //if (quem != null) { 268 | // quem.RegistrarPedido(pedido); 269 | // mensagem = $"Pedido registrado para {quem}"; 270 | //} 271 | //Console.WriteLine(mensagem); 272 | break; 273 | case 2: 274 | try { 275 | pedido = LocalizarPedido(todosOsPedidos); 276 | AdicionarComidas(pedido); 277 | } 278 | catch (InvalidOperationException ie) { 279 | Console.WriteLine(ie.Message); 280 | } 281 | catch (NullReferenceException ex) { 282 | Console.WriteLine("Pedido não existente."); 283 | } 284 | //pedido = LocalizarPedido(todosOsPedidos); 285 | //if (pedido!= null) 286 | // AdicionarComidas(pedido); 287 | //else 288 | // Console.WriteLine("Pedido não existente."); 289 | break; 290 | case 3: 291 | try { 292 | pedido = LocalizarPedido(todosOsPedidos); 293 | Console.WriteLine(pedido.Relatorio()); 294 | } 295 | catch (NullReferenceException) { 296 | Console.WriteLine("Pedido não existente."); 297 | } 298 | //pedido = LocalizarPedido(todosOsPedidos); 299 | //if (pedido != null) 300 | // Console.WriteLine(pedido.Relatorio()); 301 | //else 302 | // Console.WriteLine("Pedido não existente."); 303 | break; 304 | case 4: 305 | try { 306 | pedido = LocalizarPedido(todosOsPedidos); 307 | pedido.FecharPedido(); 308 | Console.WriteLine("Pedido encerrado: "); 309 | Console.WriteLine(pedido.Relatorio()); 310 | } 311 | catch (NullReferenceException) { 312 | Console.WriteLine("Pedido não existente."); 313 | } 314 | 315 | break; 316 | //pedido = LocalizarPedido(todosOsPedidos); 317 | //if (pedido != null) { 318 | // pedido.FecharPedido(); 319 | // Console.WriteLine("Pedido encerrado: "); 320 | // Console.WriteLine(pedido.Relatorio()); 321 | //} 322 | //else 323 | // Console.WriteLine("Pedido não existente."); 324 | //break; 325 | case 5: 326 | Cabecalho(); 327 | Console.WriteLine(todosOsPedidos.RelatorioOrdenado()); 328 | break; 329 | case 6: 330 | Cabecalho(); 331 | Console.WriteLine(baseClientes.RelatorioOrdenado()); 332 | break; 333 | case 7: 334 | Cabecalho(); 335 | //IComparable 336 | /*Comparer 337 | ComparadorDeGastos compGasto = new ComparadorDeGastos(); 338 | Console.WriteLine(baseClientes.RelatorioOrdenado(compGasto)); 339 | */ 340 | //Comparison 341 | Comparison comparacao = (cli1, cli2) 342 | => (cli1.TotalGasto()-cli2.TotalGasto()>0) ? 1 : -1 ; 343 | 344 | Console.WriteLine(baseClientes.RelatorioOrdenado(comparacao)); 345 | 346 | /*FUNÇÃO LAMBDA 347 | Console.WriteLine(baseClientes.RelatorioOrdenado( 348 | (cli1, cli2) => (cli1.TotalGasto() - cli2.TotalGasto() > 0) ? 1 : -1 349 | ) 350 | ); 351 | */ 352 | break; 353 | case 8: 354 | Cabecalho(); 355 | Func somaValorPedidos = (ped) => ped.PrecoAPagar(); 356 | double valorTotal = todosOsPedidos.Totalizador(somaValorPedidos); 357 | Console.WriteLine($"Valor total vendido no Xulambs Foods: {valorTotal:C2}"); 358 | break; 359 | case 9: 360 | Cabecalho(); 361 | baseClientes.Processar((cli) => cli.fidelizarCliente("Xulambs")); 362 | Console.WriteLine(baseClientes.RelatorioOrdenado()); 363 | break; 364 | } 365 | Pausa(); 366 | } while (opcao != 0); 367 | 368 | 369 | } 370 | 371 | 372 | } 373 | } --------------------------------------------------------------------------------