├── .gitignore ├── Codigo ├── 00_Revisao_E_Introducao_Java │ ├── 00_JavaBasico │ │ ├── .vscode │ │ │ └── settings.json │ │ ├── README.md │ │ └── src │ │ │ ├── App.java │ │ │ ├── LeituraELacos.java │ │ │ ├── Retangulo.java │ │ │ └── Strings.java │ ├── 01_MediaVetor │ │ ├── .vscode │ │ │ └── settings.json │ │ ├── README.md │ │ └── src │ │ │ └── MediaVetor.java │ └── 02_ExemplosJava │ │ ├── .vscode │ │ └── settings.json │ │ ├── README.md │ │ └── src │ │ └── RevProg.java ├── 01_Fundamentos_POO │ ├── 00_Produto │ │ ├── .vscode │ │ │ └── settings.json │ │ ├── README.md │ │ └── src │ │ │ ├── App.java │ │ │ └── Produto.java │ ├── 01_Hora_Modularidade │ │ ├── .vscode │ │ │ └── settings.json │ │ ├── README.md │ │ └── src │ │ │ ├── Hora.java │ │ │ └── HoraApp.java │ └── 02_Data_Construtores │ │ ├── .vscode │ │ └── settings.json │ │ ├── README.md │ │ └── src │ │ ├── App.java │ │ └── Data.java ├── 02_Polimorfismo │ ├── 00_HerancaPessoa │ │ ├── .vscode │ │ │ └── settings.json │ │ └── src │ │ │ ├── Administrativo.java │ │ │ ├── Aluno.java │ │ │ ├── App.java │ │ │ ├── Pessoa.java │ │ │ ├── PessoaTest.java │ │ │ └── Professor.java │ ├── 01_FormasGeometricas │ │ ├── .vscode │ │ │ └── settings.json │ │ ├── README.md │ │ └── src │ │ │ ├── Circulo.java │ │ │ ├── ConjuntoGeometrico.java │ │ │ ├── FormaGeometrica.java │ │ │ ├── FormasCollectionStream.java │ │ │ ├── FormasDemo.java │ │ │ ├── PoligonoReto.java │ │ │ ├── Quadrado.java │ │ │ ├── Retangulo.java │ │ │ └── TrianguloRetangulo.java │ └── 02_Interfaces_Amplexa │ │ ├── .vscode │ │ └── settings.json │ │ ├── README.md │ │ └── src │ │ ├── Amplexa.java │ │ ├── App.java │ │ ├── Cafeteira.java │ │ ├── Dispositivo.java │ │ ├── Geladeira.java │ │ ├── IDesligavel.java │ │ ├── IRegulavel.java │ │ └── Lampada.java └── XulambsPizza │ ├── .gitignore │ ├── .vscode │ └── settings.json │ ├── README.md │ ├── docs │ ├── diagramas │ │ ├── 00_Pizza.png │ │ └── 01_Pedido.png │ └── requisitos.md │ └── src │ ├── Comida.java │ ├── EComida.java │ ├── EDistancia.java │ ├── EEstadoPedido.java │ ├── IComida.java │ ├── Pedido.java │ ├── PedidoEntrega.java │ ├── PedidoEntregaTest.java │ ├── PedidoLocal.java │ ├── PedidoLocalTest.java │ ├── Pizza.java │ ├── Sanduiche.java │ └── XulambsFoods.java ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package and bin Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | *.bin 22 | 23 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 24 | hs_err_pid* 25 | -------------------------------------------------------------------------------- /Codigo/00_Revisao_E_Introducao_Java/00_JavaBasico/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": ["src"], 3 | "java.project.outputPath": "bin", 4 | "java.project.referencedLibraries": [ 5 | "lib/**/*.jar" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /Codigo/00_Revisao_E_Introducao_Java/00_JavaBasico/README.md: -------------------------------------------------------------------------------- 1 | ## Getting Started 2 | 3 | Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. 4 | 5 | ## Folder Structure 6 | 7 | The workspace contains two folders by default, where: 8 | 9 | - `src`: the folder to maintain sources 10 | - `lib`: the folder to maintain dependencies 11 | 12 | Meanwhile, the compiled output files will be generated in the `bin` folder by default. 13 | 14 | > If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. 15 | 16 | ## Dependency Management 17 | 18 | The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). 19 | -------------------------------------------------------------------------------- /Codigo/00_Revisao_E_Introducao_Java/00_JavaBasico/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | public static void main(String[] args) throws Exception { 3 | System.out.println("Hello, World!"); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Codigo/00_Revisao_E_Introducao_Java/00_JavaBasico/src/LeituraELacos.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * MIT License 5 | * 6 | * Copyright(c) 2025 João Caram 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | 28 | /** Java básico: E/S, repetição e decisão, vetores */ 29 | public class LeituraELacos { 30 | /** Scanner para fazer leitura da entrada padrão (teclado) */ 31 | static Scanner teclado; 32 | 33 | /** 34 | * Recebe uma mensagem para exibir e pede a leitura de um número inteiro, retornando-o. 35 | * Código sem robustez para valores não inteiros. 36 | * @param mensagem Mensagem a ser exibida ao usuário 37 | * @return Número inteiro lido a partir do teclado 38 | */ 39 | static int lerNumero(String mensagem){ 40 | int valor; 41 | System.out.print("\t"+mensagem+": "); 42 | valor = teclado.nextInt(); 43 | return valor; 44 | } 45 | 46 | /** 47 | * Preenche um vetor a partir da leitura de números inteiros 48 | * @param vetor Vetor a ser preenchido 49 | */ 50 | static void preencherVetor(int[] vetor){ 51 | for (int i = 0; i < vetor.length; i++) { 52 | vetor[i] = lerNumero("Digite um valor inteiro"); 53 | } 54 | } 55 | 56 | /** 57 | * Recebe um vetor de inteiros como parâmetro e retorna a quantidade de números pares deste vetor. 58 | * @param vetor O vetor a ser analisado. 59 | * @return int com a quantidade de pares do vetor (>=0) 60 | */ 61 | static int contaPares(int[] vetor){ 62 | int contadorPar=0; 63 | for (int i = 0; i < vetor.length; i++) { 64 | if(vetor[i]%2==0) 65 | contadorPar++; 66 | } 67 | return contadorPar; 68 | } 69 | 70 | public static void main(String[] args) throws Exception { 71 | teclado = new Scanner(System.in); 72 | int[] vetor; 73 | int tamanho = lerNumero("Quantidade de inteiros para ler"); 74 | int quantPares; 75 | 76 | vetor = new int[tamanho]; 77 | preencherVetor(vetor); 78 | quantPares = contaPares(vetor); 79 | System.out.println("O vetor tem "+quantPares+" números pares."); 80 | teclado.close(); 81 | 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Codigo/00_Revisao_E_Introducao_Java/00_JavaBasico/src/Retangulo.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * MIT License 5 | * 6 | * Copyright(c) 2024 João Caram 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | /** Primeiro exemplo de Java: E/S e impressão de um retângulo no console */ 28 | public class Retangulo { 29 | 30 | /** Scaner para leitura do teclado */ 31 | static Scanner teclado = new Scanner(System.in); 32 | 33 | /** 34 | * Lê um número inteiro do teclado, sem validação, e o retorna 35 | * @return uma variável int 36 | */ 37 | static int lerNumero(){ 38 | int valor; 39 | System.out.print("\tDigite um numero positivo: "); 40 | valor = teclado.nextInt(); 41 | return valor; 42 | } 43 | 44 | /** 45 | * Retorna uma string com uma linha de retângulo preenchida com 'X'. O tamanho é definido pelo usuário. 46 | * @param tamanho Tamanho da linha. Deve ser maior que 0 (não há validação no código) 47 | * @return String com uma linha cheia preenchida com 'X' 48 | */ 49 | static String linhaCheia(int tamanho){ 50 | String linha=""; 51 | for(int i=0; i 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | /** Java básico: E/S e algumas operações com strings */ 28 | public class Strings { 29 | 30 | /** Scanner para leitura da entrada padrão (teclado) */ 31 | static Scanner teclado; 32 | 33 | /** 34 | * Recebe uma mensagem para exibir e pede a leitura de um número inteiro, retornando-o. 35 | * Código sem robustez para valores não inteiros. 36 | * @param mensagem Mensagem a ser exibida ao usuário 37 | * @return Número inteiro lido a partir do teclado 38 | */ 39 | static int lerNumero(String mensagem){ 40 | int valor; 41 | System.out.print("\t"+mensagem+": "); 42 | valor = Integer.parseInt(teclado.nextLine()); 43 | return valor; 44 | } 45 | 46 | /** Exibe mensagem e espera leitura do teclado para simular uma pausa no programa */ 47 | static void pausa(){ 48 | System.out.println("Digite enter para continuar."); 49 | teclado.nextLine(); 50 | } 51 | 52 | /** 53 | * Exibe um menu de opções, faz a leitura de um número e a retorna para o programa principal. 54 | * @return Número inteiro lido a partir do teclado (sem robustez para valores inválidos) 55 | */ 56 | static int menu(){ 57 | System.out.println("1 - Procurar uma letra"); 58 | System.out.println("2 - Descobrir o tamanho"); 59 | System.out.println("3 - Substituir letras"); 60 | System.out.println("4 - Recortar frase"); 61 | System.out.println("5 - Contar repetição de letra"); 62 | System.out.println("0 - Sair"); 63 | 64 | int opcao = lerNumero("Digite sua opção"); 65 | return opcao; 66 | } 67 | 68 | /** 69 | * Demonstração de indexOf para localizar a ocorrência de uma letra ou substring em outra string. 70 | * Já faz a impressão do resultado para o programa principal 71 | * @param frase Frase na qual a letra será procurada. 72 | */ 73 | static void procurarLetra(String frase){ 74 | String letra; 75 | String mensagem = "Letra não existe na frase"; 76 | int posicao; 77 | System.out.print("Digite a letra para procurar: "); 78 | letra = teclado.nextLine(); 79 | posicao = frase.indexOf(letra); 80 | if(posicao!=-1) 81 | mensagem = letra + " encontrada na posição "+posicao; 82 | 83 | System.out.println("\n"+mensagem); 84 | } 85 | 86 | /** 87 | * Demonstração de replace para substituir letra de uma string, criando outra string. 88 | * Já faz a impressão do resultado para o programa principal 89 | * @param frase Frase na qual a letra será substituída. 90 | */ 91 | static void substituirLetras(String fraseOriginal){ 92 | String letraOriginal, letraNova, fraseNova; 93 | 94 | System.out.print("Digite a letra a ser substituida: "); 95 | letraOriginal = teclado.nextLine(); 96 | System.out.print("Digite a letra a ser colocada: "); 97 | letraNova = teclado.nextLine(); 98 | 99 | fraseNova = fraseOriginal.replace(letraOriginal, letraNova); 100 | 101 | System.out.println("\nOriginal: "+fraseOriginal); 102 | System.out.println("Com trocas: "+fraseNova); 103 | } 104 | 105 | /** 106 | * Demonstração de substring para recortar um trecho de uma string, retornando em outra string. 107 | * Já faz a impressão do resultado para o programa principal 108 | * @param frase Frase na qual o trecho será recortado. 109 | */ 110 | static void recortarFrase(String fraseOriginal){ 111 | String fraseNova; 112 | int posicaoInicial, posicaoFinal; 113 | System.out.println("A frase tem "+fraseOriginal.length()+" caracteres."); 114 | posicaoInicial = lerNumero("Início do recorte (>=0)"); 115 | posicaoFinal = lerNumero("Fim do recorte (<=" + fraseOriginal.length()+")"); 116 | 117 | fraseNova = fraseOriginal.substring(posicaoInicial, posicaoFinal); 118 | 119 | System.out.println("\nOriginal: "+fraseOriginal); 120 | System.out.println("Cortada: "+fraseNova); 121 | } 122 | 123 | /** 124 | * Demonstração de charAt na verificação de repetições de uma letra em uma string. 125 | * Já faz a impressão do resultado para o programa principal 126 | * @param frase Frase na qual a letra será procurada/contada. 127 | */ 128 | static void contarRepeticao(String fraseOriginal){ 129 | String letraParaContar; 130 | int contador=0; 131 | System.out.print("Digite a letra a ser contada: "); 132 | letraParaContar = teclado.nextLine(); 133 | for (int i = 0; i < fraseOriginal.length(); i++) { 134 | if(fraseOriginal.charAt(i) == letraParaContar.charAt(0)) 135 | contador++; 136 | } 137 | 138 | System.out.println("Temos "+contador+" ocorrências de "+letraParaContar+" na frase"); 139 | } 140 | 141 | 142 | public static void main(String[] args) { 143 | teclado = new Scanner(System.in); 144 | int opcao=-1; 145 | String fraseOriginal; 146 | 147 | System.out.print("Digite uma frase completa: "); 148 | fraseOriginal = teclado.nextLine(); 149 | 150 | do{ 151 | System.out.println("\n\nFrase original: "+fraseOriginal+"\n"); 152 | opcao = menu(); 153 | switch (opcao) { 154 | case 0 -> System.out.println("Adeus!!!"); 155 | case 1 -> procurarLetra(fraseOriginal); 156 | case 2 -> System.out.println("A frase "+fraseOriginal+" tem "+fraseOriginal.length()+" caracteres."); 157 | case 3 -> substituirLetras(fraseOriginal); 158 | case 4 -> recortarFrase(fraseOriginal); 159 | case 5 -> contarRepeticao(fraseOriginal); 160 | } 161 | pausa(); 162 | 163 | }while(opcao !=0); 164 | 165 | 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /Codigo/00_Revisao_E_Introducao_Java/01_MediaVetor/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": ["src"], 3 | "java.project.outputPath": "bin", 4 | "java.project.referencedLibraries": [ 5 | "lib/**/*.jar" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /Codigo/00_Revisao_E_Introducao_Java/01_MediaVetor/README.md: -------------------------------------------------------------------------------- 1 | ## Getting Started 2 | 3 | Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. 4 | 5 | ## Folder Structure 6 | 7 | The workspace contains two folders by default, where: 8 | 9 | - `src`: the folder to maintain sources 10 | - `lib`: the folder to maintain dependencies 11 | 12 | Meanwhile, the compiled output files will be generated in the `bin` folder by default. 13 | 14 | > If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. 15 | 16 | ## Dependency Management 17 | 18 | The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). 19 | -------------------------------------------------------------------------------- /Codigo/00_Revisao_E_Introducao_Java/01_MediaVetor/src/MediaVetor.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class MediaVetor { 4 | public static void main(String[] args) throws Exception { 5 | Scanner teclado; 6 | double[] vetor; 7 | int tamanhoVetor; 8 | double soma; 9 | double media; 10 | 11 | teclado = new Scanner(System.in); 12 | System.out.print("Qual o tamanho do vetor a ser lido? "); 13 | 14 | tamanhoVetor = Integer.parseInt(teclado.nextLine()); 15 | vetor = new double[tamanhoVetor]; 16 | System.out.println(); 17 | 18 | for (int i = 0; i < tamanhoVetor; i++){ 19 | System.out.print("Digite o valor " + (i + 1) + ": "); 20 | vetor[i] = Double.parseDouble(teclado.nextLine()); 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 | System.out.println("O vetor tem "+tamanhoVetor+" elementos. A soma dos elementos é "+soma); 31 | System.out.println("A média dos valores do vetor é de " + String.format("%.2f", media)); 32 | 33 | teclado.close(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Codigo/00_Revisao_E_Introducao_Java/02_ExemplosJava/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": ["src"], 3 | "java.project.outputPath": "bin", 4 | "java.project.referencedLibraries": [ 5 | "lib/**/*.jar" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /Codigo/00_Revisao_E_Introducao_Java/02_ExemplosJava/README.md: -------------------------------------------------------------------------------- 1 | ## Getting Started 2 | 3 | Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. 4 | 5 | ## Folder Structure 6 | 7 | The workspace contains two folders by default, where: 8 | 9 | - `src`: the folder to maintain sources 10 | - `lib`: the folder to maintain dependencies 11 | 12 | Meanwhile, the compiled output files will be generated in the `bin` folder by default. 13 | 14 | > If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. 15 | 16 | ## Dependency Management 17 | 18 | The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). 19 | -------------------------------------------------------------------------------- /Codigo/00_Revisao_E_Introducao_Java/02_ExemplosJava/src/RevProg.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class RevProg { 4 | 5 | static Scanner teclado; 6 | 7 | /** 8 | * "Limpa" a tela (códigos de terminal VT-100) 9 | */ 10 | public static void limparTela() { 11 | System.out.print("\033[H\033[2J"); 12 | System.out.flush(); 13 | } 14 | 15 | /** 16 | * Pausa para leitura de mensagens em console 17 | */ 18 | static void pausa() { 19 | System.out.println("Enter para continuar."); 20 | teclado.nextLine(); 21 | } 22 | 23 | /** 24 | * Encapsula uma leitura de teclado, com mensagem personalizada. A mensagem sempre é completada com ":". Retorna um inteiro. 25 | * @param mensagem A mensagem a ser exibida, sem pontuação final. 26 | * @return String convertida em inteiro (int). 27 | */ 28 | public static int leituraInteiro(String mensagem){ 29 | System.out.print("\n"+mensagem+": "); 30 | return Integer.parseInt(teclado.nextLine()); 31 | } 32 | 33 | 34 | /** 35 | * Ver o enunciado do exercício no Canvas. 36 | */ 37 | public static void exercicio01(){ 38 | int largura = leituraInteiro("Largura do retângulo"); 39 | int altura = leituraInteiro("Altura do retângulo"); 40 | imprimirRetangulo(largura, altura); 41 | } 42 | 43 | /** 44 | * Usa os métodos {@link #imprimirLinhaCheia(int, int) imprimirLinhaCheia} e {@link #imprimirLinhaVazada(int, int) imprimirLinhaVazada} 45 | * para desenhar um retângulo na tela. O caractere usado para a borda está fixo em '#' 46 | * @param largura A largura do retângulo 47 | * @param altura A altura do retângulo 48 | */ 49 | public static void imprimirRetangulo(int largura, int altura){ 50 | imprimirLinhaCheia(largura, '_'); 51 | for (int i = 0; i < altura-2; i++) { 52 | imprimirLinhaVazada(largura, '|'); 53 | } 54 | imprimirLinhaCheia(largura, '-'); 55 | 56 | } 57 | 58 | /** 59 | * Imprime uma linha preenchida pelo caractere 'borda', com a largura especificada. 60 | * @param largura Qual a largura da linha 61 | * @param borda O caractere para ser a 'borda' da linha 62 | */ 63 | public static void imprimirLinhaCheia(int largura, char borda){ 64 | for (int i = 0; i < largura; i++) { 65 | System.out.print(borda); 66 | } 67 | System.out.println(); 68 | } 69 | 70 | /** 71 | * Imprime uma linha vazada por espaços, usando o caractere 'borda' nas extremidades, com a largura especificada. 72 | * @param largura Qual a largura da linha 73 | * @param borda O caractere para ser a 'borda' da linha 74 | */ 75 | public static void imprimirLinhaVazada(int largura, char borda){ 76 | System.out.print(borda); 77 | for (int i = 0; i < largura-2; i++) { 78 | System.out.print(" "); 79 | } 80 | System.out.println(borda); 81 | } 82 | 83 | 84 | /** 85 | * Ver o enunciado do exercício no Canvas. 86 | */ 87 | public static void exercicio02(){ 88 | int tamanhoTabua = leituraInteiro("Tamanho da tábua em metros"); 89 | int quantPedacos = leituraInteiro("Total de pedaços a cortar"); 90 | int quantidadeTabuas = quantidadeAComprar(tamanhoTabua, quantPedacos); 91 | int sobraCorte = sobraDeMaterial(tamanhoTabua, quantPedacos); 92 | 93 | System.out.println("Será necessário comprar "+quantidadeTabuas+" tábuas de "+tamanhoTabua+"m."); 94 | System.out.println("Sobrarão "+sobraCorte+" cm de tábua."); 95 | } 96 | 97 | /** 98 | * Calcula a quantidade de tábuas a comprar para cortar 'quantPedacos' de madeira de 45cm cada. Método desprotegido: não faz validação de valores negativos. 99 | * @param tamanhoTabua Tamanho da tábua em metros (inteiro) 100 | * @param quantPedacos Quantos pedaços de 45cm cada serão necessários. 101 | * @return Valor inteiro com a quantidade de tábuas necessárias para 'quantPedacos' de madeira. 102 | */ 103 | public static int quantidadeAComprar(int tamanhoTabua, int quantPedacos){ 104 | int tamanhoTotal = quantPedacos * 45; 105 | int tabuaEmCm = tamanhoTabua * 100; 106 | 107 | int quantidade = (tamanhoTotal/tabuaEmCm); 108 | int resto = (tamanhoTotal%tabuaEmCm); 109 | if(resto>0) 110 | quantidade++; 111 | 112 | return quantidade; 113 | } 114 | 115 | /** 116 | * Calcula a sobra de material, em cm, para se criar 'quantPedacos' de 45cm a partir de tábuas com comprimento 'tamanhoTabua'. 117 | * Método desprotegido: não faz validação de valores negativos. 118 | * @param tamanhoTabua Tamanho da tábua em metros (inteiro) 119 | * @param quantPedacos Quantos pedaços de 45cm cada serão necessários. 120 | * @return Valor inteiro com a sobra de madeira, em centímetros. 121 | */ 122 | public static int sobraDeMaterial(int tamanhoTabua, int quantPedacos){ 123 | int tamanhoTotal = quantPedacos * 45; 124 | int tabuaEmCm = tamanhoTabua * 100; 125 | 126 | int quantidade = quantidadeAComprar(tamanhoTabua, quantPedacos); 127 | int sobra = (quantidade * tabuaEmCm) % tamanhoTotal; 128 | 129 | return sobra; 130 | } 131 | 132 | /** 133 | * Ver o enunciado do exercício no Canvas. 134 | * O método lê 5 números e em seguida imprime o resultado da rifa fazendo a impressão de cada um dos dígitos extraídos, 135 | * sem armazenar o resultado. 136 | */ 137 | public static void exercicio03(){ 138 | int[] premios = new int[5]; 139 | for (int i = 0; i < premios.length; i++) { 140 | premios[i] = leituraInteiro("Digite o valor do "+(i+1)+"º prêmio, com 5 dígitos"); 141 | } 142 | System.out.print("O prêmio da rifa é: "); 143 | for (int i = 0; i < premios.length; i++) { 144 | System.out.print(extrairDigito(i+1, premios[i])); 145 | } 146 | System.out.println(); 147 | } 148 | 149 | /** 150 | * Extrai um dígito de um valor inteiro numérico de 5 dígitos a partir da escolha da posição. 151 | * Este método considera que o dígito mais à esquerda do valor original é a posição 1. São feitas operações de divisão e resto para 152 | * obtenção do resultado. Por exemplo, posição 3 do valor 46138 : 46138/10^(5-3) = 46138/10^2 = 46138/100 = 461. Em seguida, 153 | * 461 % 10 = 1 (3º dígito do valor original). O método não está protegido contra posições inválidas. 154 | * @param posicao Posição do dígito a ser extraído. O dígito mais à esquerda é considerada a posição 1. 155 | * @param valorOriginal O valor original, obrigatoriamente com 5 dígitos. 156 | * @return Um número inteiro representando o dígito na posição desejada do valor original. 157 | */ 158 | public static int extrairDigito(int posicao, int valorOriginal){ 159 | int potencia = 5 - posicao; 160 | int fatorDivisao = (int)Math.pow(10, potencia); 161 | int valor = valorOriginal / fatorDivisao; 162 | return valor % 10; 163 | } 164 | 165 | public static void main(String[] args) throws Exception { 166 | teclado = new Scanner(System.in); 167 | 168 | exercicio02(); 169 | teclado.close(); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /Codigo/01_Fundamentos_POO/00_Produto/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": ["src"], 3 | "java.project.outputPath": "bin", 4 | "java.project.referencedLibraries": [ 5 | "lib/**/*.jar" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /Codigo/01_Fundamentos_POO/00_Produto/README.md: -------------------------------------------------------------------------------- 1 | ## Getting Started 2 | 3 | Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. 4 | 5 | ## Folder Structure 6 | 7 | The workspace contains two folders by default, where: 8 | 9 | - `src`: the folder to maintain sources 10 | - `lib`: the folder to maintain dependencies 11 | 12 | Meanwhile, the compiled output files will be generated in the `bin` folder by default. 13 | 14 | > If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. 15 | 16 | ## Dependency Management 17 | 18 | The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). 19 | -------------------------------------------------------------------------------- /Codigo/01_Fundamentos_POO/00_Produto/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class App { 4 | public static void main(String[] args) throws Exception { 5 | Scanner teclado = new Scanner(System.in); 6 | Produto prod1 = new Produto(); 7 | int quantidade; 8 | prod1.registrar("Chá mate com gás", 2.99); 9 | System.out.print("Quantas unidades você quer comprar? "); 10 | quantidade = Integer.parseInt(teclado.nextLine()); 11 | System.out.println(quantidade+ " unidades de "+prod1.descricao+ 12 | " custam R$ "+prod1.valorLote(quantidade)); 13 | 14 | teclado.close(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Codigo/01_Fundamentos_POO/00_Produto/src/Produto.java: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2022-24 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 | public class Produto { 26 | String descricao; 27 | double valorUnitario; 28 | 29 | /** 30 | * Registra um produto com descrição e valor unitário. 31 | * A descricão tem pelo menos 2 caracteres e o valor unitário mínimo é R$0,01. 32 | * Em caso de violação das regras, o produto ficará "Sem descrição" e com valor de R$0,01. 33 | * @param desc Descrição do produto (mínimo 2 caracteres) 34 | * @param valor Preço unitário (mínimo R$0,01) 35 | */ 36 | public void registrar(String desc, double valor){ 37 | descricao = desc; 38 | valorUnitario = valor; 39 | if(descricao.length()<2) 40 | descricao = "Sem descrição"; 41 | if(valorUnitario<=0d) 42 | valorUnitario = 0.01; 43 | } 44 | 45 | /** 46 | * Calcula o preço de venda de um lote de "quant" produtos. 47 | * Em caso de quantidade não positiva, retorna 0. 48 | * @param quant Quantidade de produtos a ser vendida (>0) 49 | * @return Double com o valor do lote, ou valor 0.0 em caso de lote/quantidade inválida. 50 | */ 51 | public double valorLote(int quant){ 52 | double resposta = 0d; 53 | if(quant >0 ) 54 | resposta = valorUnitario * quant; 55 | return resposta; 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /Codigo/01_Fundamentos_POO/01_Hora_Modularidade/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": ["src"], 3 | "java.project.outputPath": "bin", 4 | "java.project.referencedLibraries": [ 5 | "lib/**/*.jar" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /Codigo/01_Fundamentos_POO/01_Hora_Modularidade/README.md: -------------------------------------------------------------------------------- 1 | ## Getting Started 2 | 3 | Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. 4 | 5 | ## Folder Structure 6 | 7 | The workspace contains two folders by default, where: 8 | 9 | - `src`: the folder to maintain sources 10 | - `lib`: the folder to maintain dependencies 11 | 12 | Meanwhile, the compiled output files will be generated in the `bin` folder by default. 13 | 14 | > If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. 15 | 16 | ## Dependency Management 17 | 18 | The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). 19 | -------------------------------------------------------------------------------- /Codigo/01_Fundamentos_POO/01_Hora_Modularidade/src/Hora.java: -------------------------------------------------------------------------------- 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 | /** 26 | * Primeira versão da classe Hora para demonstração de conceitos básicos de classe e objetos: atributos, métodos, parâmetros, documentação. 27 | * Esta classe tem a responsabilidade de armazenar um horário do dia, considerando 24h. 28 | * Pode e deve ser melhorada com futuros conhecimentos. 29 | */ 30 | public class Hora { 31 | 32 | //#region atributos 33 | 34 | int horas; 35 | int minutos; 36 | int segundos; 37 | 38 | //#endregion 39 | 40 | //#region métodos 41 | 42 | /** 43 | * Ajusta uma hora para o valor desejado de horas, minutos e segundos. Em caso de valores inválidos, a hora retorna para 00:00:00. 44 | * @param hora A hora desejada (0 a 23) 45 | * @param minuto O minuto desejado (0 a 59) 46 | * @param segundo O segundo desejado (0 a 59) 47 | */ 48 | void ajustar(int hora, int minuto, int segundo){ 49 | this.horas = hora; 50 | this.minutos = minuto; 51 | this.segundos = segundo; 52 | if(!validar()) 53 | this.horas = this.minutos = this.segundos = 0; 54 | } 55 | 56 | /** 57 | * Valida a hora armazenada atualmente, de acordo com as regras habituais de hora, minuto e segundo. Retorna TRUE ou FALSE conforme validade da hora. 58 | * @return TRUE para hora válida, FALSE para hora inválida. 59 | */ 60 | boolean validar() { 61 | //TODO: revisar código e melhorar lógica 62 | boolean resposta = false; 63 | if ((horas >= 0 && horas <= 23) && 64 | (minutos >= 0 && minutos <= 59) && 65 | (segundos >= 0 && segundos <= 59)) 66 | resposta = true; 67 | 68 | return resposta; 69 | } 70 | 71 | /** 72 | * Incrementa uma quantidade de segundos a uma hora existente, retornando a nova hora. Não modifica a hora já existente. 73 | * Quantidades menores ou iguais a 0 são ignoradas e é retornada uma hora idêntica à atual. 74 | * @param quantidadeSegundos Quantidade de segundos a incrementar (>0) 75 | * @return Uma nova hora com os segundos incrementados, podendo ser igual à hora atual em caso de valores não positivos. 76 | */ 77 | Hora incrementar(int quantidadeSegundos){ 78 | //TODO: revisar código e melhorar lógica 79 | int minutosParaSegundos = 60; 80 | int horasParaMinutos = 60; 81 | int horasParaSegundos = minutosParaSegundos * horasParaMinutos; 82 | Hora novaHora = new Hora(); 83 | novaHora.ajustar(horas, minutos, segundos); 84 | 85 | if(quantidadeSegundos > 0){ 86 | int totalSegundos = (horas * horasParaSegundos + minutos * minutosParaSegundos + segundos) + quantidadeSegundos; 87 | int novosSegundos = totalSegundos % 60; 88 | 89 | int novosMinutos = (totalSegundos / minutosParaSegundos) % horasParaMinutos; 90 | int novasHoras = (totalSegundos / horasParaSegundos) % 24; 91 | 92 | novaHora.ajustar(novasHoras, novosMinutos, novosSegundos); 93 | } 94 | return novaHora; 95 | } 96 | 97 | 98 | 99 | /** 100 | * Verifica se esta hora encontra-se à frente de outra considerando um dia de 24h. Retorna TRUE ou FALSE conforme esta hora esteja na frente. 101 | * Perceba que a ação é feita a partir da conversão de todos os valores para segundos, seguida de uma comparação simples. Há outras maneiras de resolver ;-) 102 | * @param outra A outra hora a ser comparada com esta 103 | * @return TRUE se esta hora está à frente no relógio, FALSE caso contrário. 104 | */ 105 | boolean estahNaFrenteDe(Hora outra){ 106 | //TODO: revisar código e melhorar lógica 107 | int minutosParaSegundos = 60; 108 | int horasParaSegundos = minutosParaSegundos * 60; 109 | 110 | int esta; 111 | esta = (horas * horasParaSegundos + minutos * minutosParaSegundos + segundos); 112 | int aquela; 113 | aquela = outra.horas * horasParaSegundos + outra.minutos * minutosParaSegundos + outra.segundos; 114 | return (esta > aquela); 115 | } 116 | 117 | /** 118 | * Retorna uma hora formatada em HH:MM:SS 119 | * @return Uma string com a hora formatada como indicado. 120 | */ 121 | String horaFormatada(){ 122 | return String.format("%02d:%02d:%02d", horas, minutos, segundos); 123 | } 124 | //#endregion 125 | } 126 | -------------------------------------------------------------------------------- /Codigo/01_Fundamentos_POO/01_Hora_Modularidade/src/HoraApp.java: -------------------------------------------------------------------------------- 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 | import java.util.Scanner; 26 | 27 | /** 28 | * Demonstração do uso de objetos da classe Hora em um programa/app. 29 | * Este programa nada mais faz além de testar algumas operações da classe (o que aprenderemos a fazer melhor posteriormente). 30 | */ 31 | public class HoraApp { 32 | 33 | public static void main(String[] args) { 34 | Scanner teclado = new Scanner(System.in); 35 | Hora hora; 36 | Hora hora2; 37 | int horas; 38 | int minutos; 39 | int segundos; 40 | int incremento; 41 | String horaDoUsuario; 42 | 43 | System.out.print("Por favor, digite um horário válido (HH:MM:SS): "); 44 | horaDoUsuario = teclado.nextLine(); 45 | 46 | String[] detalhesHora = horaDoUsuario.split(":"); 47 | horas = Integer.parseInt(detalhesHora[0]); 48 | minutos = Integer.parseInt(detalhesHora[1]); 49 | segundos = Integer.parseInt(detalhesHora[2]); 50 | 51 | hora = new Hora(); 52 | hora.ajustar(horas, minutos, segundos); 53 | 54 | System.out.print("Sua hora escolhida: "); 55 | System.out.println(hora.horaFormatada()); 56 | 57 | System.out.print("\nPor favor, digite um incremento em segundos positivos: "); 58 | incremento = Integer.parseInt(teclado.nextLine()); 59 | 60 | hora2 = hora.incrementar(incremento); 61 | 62 | System.out.printf("%s é sua hora original e %s é sua hora com incremento de %d segundos\n" 63 | , hora.horaFormatada(), hora2.horaFormatada(), incremento); 64 | 65 | System.out.printf("%s está na frente de %s? ", hora.horaFormatada(), hora2.horaFormatada()); 66 | System.out.println(hora.estahNaFrenteDe(hora2)); 67 | 68 | System.out.printf("%s está na frente de %s? ", hora2.horaFormatada(), hora.horaFormatada()); 69 | System.out.println(hora2.estahNaFrenteDe(hora)); 70 | 71 | System.out.print("Ajustando a hora para 19:08:24: "); 72 | hora.ajustar(19, 8, 24); 73 | System.out.println(hora.horaFormatada()); 74 | 75 | teclado.close(); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /Codigo/01_Fundamentos_POO/02_Data_Construtores/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": ["src"], 3 | "java.project.outputPath": "bin", 4 | "java.project.referencedLibraries": [ 5 | "lib/**/*.jar" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /Codigo/01_Fundamentos_POO/02_Data_Construtores/README.md: -------------------------------------------------------------------------------- 1 | ## Getting Started 2 | 3 | Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code. 4 | 5 | ## Folder Structure 6 | 7 | The workspace contains two folders by default, where: 8 | 9 | - `src`: the folder to maintain sources 10 | - `lib`: the folder to maintain dependencies 11 | 12 | Meanwhile, the compiled output files will be generated in the `bin` folder by default. 13 | 14 | > If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there. 15 | 16 | ## Dependency Management 17 | 18 | The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies). 19 | -------------------------------------------------------------------------------- /Codigo/01_Fundamentos_POO/02_Data_Construtores/src/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | public static void main(String[] args) throws Exception { 3 | Data data1 = new Data(4,23,2024); 4 | 5 | System.out.println(data1.dataFormatada()); 6 | 7 | data1 = new Data(12, 10); 8 | System.out.println(data1.dataFormatada()); 9 | 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Codigo/01_Fundamentos_POO/02_Data_Construtores/src/Data.java: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2022-24 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 | public class Data { 26 | 27 | //#region atributos 28 | 29 | private int dia; 30 | private int mes; 31 | private int ano; 32 | //#endregion 33 | 34 | /** 35 | * Construtor detalhado. Tenta criar uma data com os valores passados 36 | * de dia, mês e ano. O ano deve ser de 1900 em diante. Qualquer dado inválido 37 | * leva a data para 01/01/2000 38 | * @param dia De 1 a 31, de acordo com o mês 39 | * @param mes De 1 a 12 40 | * @param ano De 1900 em diante 41 | */ 42 | public Data(int dia, int mes, int ano){ 43 | ajustar(dia, mes, ano); 44 | } 45 | 46 | /** 47 | * Construtor para o ano atual. Tenta criar uma data com os valores passados 48 | * de dia e mês e inclui o ano atual. Qualquer dado inválido 49 | * leva a data para 01/01/2000 50 | * @param dia De 1 a 31, de acordo com o mês 51 | * @param mes De 1 a 12 52 | */ 53 | public Data(int dia, int mes){ 54 | int anoAtual = 2024; 55 | ajustar(dia, mes, anoAtual); 56 | } 57 | /** 58 | * Tenta ajustar uma data com os valores passados. Em caso de qualquer valor inválido, retorna para a data padrão de 01/01/2000 59 | * @param dia O dia da data (1 a 31, de acordo com o mês). Os anos válidos são de 1900 em diante. 60 | * @param mes O mês da data (1 a 12) 61 | * @param ano O ano da data (de 1900 em diante) 62 | */ 63 | public void ajustar(int dia, int mes, int ano){ 64 | this.dia = dia; 65 | this.mes = mes; 66 | this.ano = ano; 67 | if(!ehDataValida()){ 68 | this.dia = this.mes = 1; 69 | this.ano = 2000; 70 | } 71 | } 72 | 73 | /** 74 | * Verifica se a data armazenada é válida (método privado) 75 | * @return TRUE se é válida ; FALSE se não é válida 76 | */ 77 | private boolean ehDataValida(){ 78 | int[] DIASDOMES = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 79 | 80 | boolean resposta = true; //resposta sobre a validade 81 | if(this.ano<1900) 82 | resposta = false; 83 | else{ 84 | if (this.mes < 1 || this.mes > 12) //mês<1 ou mês>12 --> data inválida 85 | resposta = false; 86 | else { 87 | if (this.ehAnoBissexto()) //senão, caso de 29/02 em ano bissexto --> data válida 88 | DIASDOMES[2] = 29; 89 | if (this.dia > DIASDOMES[this.mes]) //senao, verifica validade de acordo com o mês atual 90 | resposta = false; 91 | DIASDOMES[2] = 28; 92 | } 93 | } 94 | return resposta; //retorna a resposta obtida 95 | } 96 | 97 | /** 98 | * Retorna se o ano da data armazenada é bissexto 99 | * Para regras do ano bissexto: 100 | * http://educacao.uol.com.br/disciplinas/matematica/ano-bissexto-eles-se-repetem-a-cada-4-anos.htm 101 | * http://www.sogeografia.com.br/Curiosidades/?pg=4 102 | * @return Se o ano é bissexto (true) ou não (false) 103 | */ 104 | private boolean ehAnoBissexto(){ 105 | boolean resposta = false; 106 | if(this.ano%400==0) 107 | resposta = true; 108 | else if(this.ano%4==0 && this.ano%100!=0) 109 | resposta = true; 110 | 111 | return resposta; 112 | } 113 | 114 | /** 115 | * Acrescenta alguns dias à data e retorna a nova data (sem modificar a atual) 116 | * @param quant Quantos dias 117 | * @return Nova data com os dias adicionados 118 | */ 119 | public Data somarDias(int quantos){ 120 | int[] DIASDOMES = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 121 | Data aux = new Data(this.dia, this.mes, this.ano); 122 | 123 | 124 | if(quantos<=0) //não pode acrescentar dias negativos e, assim, retorna data atual. 125 | return aux; 126 | 127 | aux.dia += quantos; //acrescenta a quantidade ao dia atual e, em seguida, devemos ajustar mês e ano 128 | 129 | if (aux.ehAnoBissexto()) DIASDOMES[2] = 29; //se o ano é bissexto, altera fevereiro para 29 dias 130 | 131 | while (aux.dia > DIASDOMES[aux.mes]){ //enquanto os dias ultrapassam o limite de dias do mês atual... ajustar 132 | 133 | aux.dia = aux.dia - DIASDOMES[aux.mes]; // desconta a quantidade de dias do mês 134 | aux.mes++; //avança o mês 135 | 136 | if (aux.mes > 12){ //se passar de 12 meses... 137 | aux.mes = aux.mes - 12; //desconta-se 1 ano 138 | aux.ano++; //avança o ano. 139 | if (aux.ehAnoBissexto()) DIASDOMES[2] = 29; //verifica se o novo ano é bissexto para ajustar os dias de fevereiro. 140 | else DIASDOMES[2] = 28; 141 | } 142 | } 143 | return aux; 144 | } 145 | 146 | /** 147 | * Verifica se esta data está antes de outra, considerando o calendário. Retorna um booleano TRUE se esta for antes. 148 | * Comparação feita pela transformação da data em String AAAAMMDD 149 | * @param outra Outra data a ser comparada 150 | * @return TRUE se esta for futura, FALSE caso contrário 151 | */ 152 | public boolean estahAntesDe(Data outra){ 153 | boolean resposta = false; 154 | 155 | String esta = String.format("%4d", this.ano)+String.format("%2d", this.mes)+String.format("%2d", this.dia); 156 | String aOutra = String.format("%4d", outra.ano)+String.format("%2d", outra.mes)+String.format("%2d", outra.dia); 157 | 158 | if(esta.compareTo(aOutra)>0) 159 | resposta = true; 160 | 161 | return resposta; 162 | } 163 | 164 | /** 165 | * Retorna a data formatada 166 | * @return String com a data no formato dd/mm/aaaa 167 | */ 168 | public String dataFormatada(){ 169 | return (String.format("%02d",this.dia)+ "/" 170 | + String.format("%02d",this.mes)+ "/" 171 | + String.format("%4d",this.ano)); 172 | } 173 | 174 | 175 | 176 | 177 | } 178 | 179 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/00_HerancaPessoa/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": ["src"], 3 | "java.project.outputPath": "bin", 4 | "java.project.referencedLibraries": [ 5 | "lib/**/*.jar" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/00_HerancaPessoa/src/Administrativo.java: -------------------------------------------------------------------------------- 1 | import java.time.LocalDate; 2 | 3 | public class Administrativo extends Pessoa{ 4 | 5 | private static double salarioBase = 2500.0; 6 | private double valorGratificacao; 7 | 8 | public Administrativo(String nome, LocalDate nascimento, String doc, double gratif){ 9 | super(nome, nascimento, doc); 10 | if(gratif > 0) 11 | valorGratificacao = gratif; 12 | } 13 | 14 | public double salarioBruto(){ 15 | return salarioBase + valorGratificacao; 16 | } 17 | 18 | @Override 19 | public String dadosPessoa(){ 20 | return super.dadosPessoa()+" Funcionário administrativo com salário de R$ " +salarioBruto(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/00_HerancaPessoa/src/Aluno.java: -------------------------------------------------------------------------------- 1 | import java.time.LocalDate; 2 | 3 | public class Aluno extends Pessoa{ 4 | 5 | private static double horaAula = 28.5; 6 | private double valorMatricula; 7 | 8 | public Aluno(String nome, LocalDate nascimento, String doc, double mat){ 9 | super(nome, nascimento, doc); 10 | if(mat >0) 11 | this.valorMatricula = mat; 12 | } 13 | 14 | public double valorMensalidade(){ 15 | return ((horaAula * cargaHoraria) - valorMatricula) / 6.0; 16 | } 17 | 18 | @Override 19 | public String dadosPessoa(){ 20 | return super.dadosPessoa() + " Mensalidade: R$ "+valorMensalidade(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/00_HerancaPessoa/src/App.java: -------------------------------------------------------------------------------- 1 | import java.time.LocalDate; 2 | 3 | public class App { 4 | public static void main(String[] args) throws Exception { 5 | Pessoa[] todoMundo = new Pessoa[20]; 6 | 7 | todoMundo[0] = new Pessoa("Pessoa Joao", 8 | LocalDate.of(2000, 1, 1), 9 | "Pess1"); 10 | 11 | todoMundo[1] = new Pessoa("Pessoa Joana", 12 | LocalDate.of(2010, 1, 1), 13 | "Pess2"); 14 | 15 | todoMundo[2] = new Aluno("Aluna Maria", 16 | LocalDate.of(2003,10,1), 17 | "Alun1", 1000); 18 | todoMundo[2].setCargaHoraria(300); 19 | 20 | todoMundo[3] = new Professor("Prof Pardal", 21 | LocalDate.of(1983,5,1), 22 | "Prof1"); 23 | todoMundo[3].setCargaHoraria(32); 24 | 25 | todoMundo[4] = new Administrativo("Secretária Geral", 26 | LocalDate.of(1992,5,1), 27 | "Sec1", 1000); 28 | todoMundo[4].setCargaHoraria(32); 29 | 30 | for (Pessoa pessoa : todoMundo) { 31 | if(pessoa!=null) 32 | System.out.println(pessoa.dadosPessoa()); 33 | } 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/00_HerancaPessoa/src/Pessoa.java: -------------------------------------------------------------------------------- 1 | import java.time.LocalDate; 2 | import java.time.Period; 3 | import java.util.Random; 4 | 5 | public class Pessoa { 6 | static Random sorteio = new Random(42); 7 | protected int id; 8 | protected String nome; 9 | protected String documento; 10 | protected LocalDate dataNasc; 11 | protected String email; 12 | protected int cargaHoraria; 13 | 14 | public Pessoa(String nome, LocalDate nascimento, String documento) { 15 | this.nome = nome; 16 | this.dataNasc = nascimento; 17 | this.documento = documento; 18 | this.id = sorteio.nextInt() % 1_000_000; 19 | } 20 | 21 | public void setCargaHoraria(int cargaHoraria) { 22 | if (cargaHoraria > 0) 23 | this.cargaHoraria = cargaHoraria; 24 | } 25 | 26 | public int idade() { 27 | LocalDate hoje = LocalDate.now(); 28 | 29 | Period intervalo = dataNasc.until(hoje); 30 | 31 | return intervalo.getYears(); 32 | } 33 | 34 | public void enviarEmail(String texto) { 35 | // fingindo que estou usando um serviço bacanudo para enviar emails 36 | } 37 | 38 | public String dadosPessoa(){ 39 | return nome+", idade: "+idade()+" anos."; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/00_HerancaPessoa/src/PessoaTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.assertEquals; 2 | import java.time.LocalDate; 3 | import org.junit.jupiter.api.BeforeAll; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class PessoaTest { 7 | 8 | static Pessoa pessoa; 9 | 10 | @BeforeAll 11 | public static void setUp(){ 12 | pessoa = new Pessoa("Pessoa1", LocalDate.of(2000, 1, 1), "Doc1"); 13 | } 14 | 15 | @Test 16 | public void calculaIdadeJaCompletada(){ 17 | assertEquals(24, pessoa.idade()); 18 | } 19 | 20 | @Test 21 | public void calculaIdadeIncompleta(){ 22 | pessoa = new Pessoa("Pessoa1", LocalDate.of(2000, 6, 1), "Doc1"); 23 | assertEquals(23, pessoa.idade()); 24 | } 25 | 26 | @Test 27 | public void calculaIdadeHoje(){ 28 | pessoa = new Pessoa("Pessoa1", LocalDate.of(2000, 4, 1), "Doc1"); 29 | assertEquals(24, pessoa.idade()); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/00_HerancaPessoa/src/Professor.java: -------------------------------------------------------------------------------- 1 | import java.time.LocalDate; 2 | 3 | public class Professor extends Pessoa { 4 | 5 | private static double horaAula = 35d; 6 | 7 | public Professor(String nome, LocalDate nasc, String doc){ 8 | super(nome, nasc, doc); 9 | } 10 | 11 | public double salarioBruto(){ 12 | return cargaHoraria * horaAula * 1.20; 13 | } 14 | 15 | @Override 16 | public String dadosPessoa(){ 17 | return super.dadosPessoa() + " Salário bruto: R$ "+salarioBruto(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/01_FormasGeometricas/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": ["src"], 3 | "java.project.outputPath": "bin", 4 | "java.project.referencedLibraries": [ 5 | "lib/**/*.jar" 6 | ] 7 | } 8 | 9 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/01_FormasGeometricas/README.md: -------------------------------------------------------------------------------- 1 | # Polimorfismo de inclusão e Classes Abstratas 2 | 3 | João está aprendendo geometria plana, mas tem preguiça de fazer contas. Como ele também está aprendendo a programar, ele deseja criar um pequeno sistema que o ajude a calcular áreas e perímetros de diversas formas geométricas. Este sistema deve permitir que João armazene as formas geométricas em um conjunto e faça a comparação de suas áreas para saber quem é a maior. 4 | 5 | Pareceu bom para João começar com quadrados, retângulos, triângulos retângulos e círculos. 6 | 7 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/01_FormasGeometricas/src/Circulo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2023 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 | 26 | public class Circulo extends FormaGeometrica{ 27 | private double raio; 28 | 29 | /** 30 | * Construtor. O raio mínimo do círculo é 1. 31 | * @param raio Raio do círculo. Valores menores que 1 são convertidos em 1. 32 | */ 33 | public Circulo(double raio){ 34 | super("CÍRCULO"); 35 | this.raio = raio; 36 | if(this.raio<=1) 37 | this.raio=1d; 38 | } 39 | 40 | 41 | /** 42 | * Calcula e retorna a área do círculo 43 | * @return Área do círculo (double) 44 | */ 45 | @Override 46 | public double area(){ 47 | return Math.PI*Math.pow(this.raio, 2.0); 48 | } 49 | 50 | /** 51 | * Calcula e retorna o perímetro do círculo 52 | * @return Perímetro do círculo (double) 53 | */ 54 | @Override 55 | public double perimetro(){ 56 | return 2*Math.PI*this.raio; 57 | } 58 | 59 | /** 60 | * Retorna a String com a descrição do círculo (descrição, área e raio) 61 | * @return String com a descrição conforme especificado. 62 | */ 63 | @Override 64 | public String toString(){ 65 | return super.toString() + String.format(" | Raio: %05.2f",raio); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/01_FormasGeometricas/src/ConjuntoGeometrico.java: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2023 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 | /** Encapsula um conjunto de formas geométricas */ 26 | public class ConjuntoGeometrico { 27 | 28 | private FormaGeometrica[] formas; 29 | int quantidade; 30 | 31 | /** 32 | * Cria um conjunto vazio de formas. A capacidade mínima do conjunto é 2. 33 | * @param capacidade Capacidade do conjunto. Valores menores que 2 viram 2. 34 | */ 35 | public ConjuntoGeometrico(int capacidade) { 36 | if(capacidade <2) capacidade = 2; 37 | formas = new FormaGeometrica[capacidade]; 38 | quantidade = 0; 39 | } 40 | 41 | /** 42 | * Retorna a forma com a maior área dentro do conjunto. Pode retornar nulo, se o conjunto estiver vazio. 43 | * @return A forma com a maior área do conjunto, ou nulo se ele estiver vazio. 44 | */ 45 | public FormaGeometrica maiorArea() { 46 | FormaGeometrica maior = formas[0]; 47 | for (int i = 1; i < quantidade; i++) { 48 | if(formas[i].area() > maior.area()) 49 | maior = formas[i]; 50 | } 51 | return maior; 52 | } 53 | 54 | /** 55 | * Caso tenha espaço, armazena uma forma no conjunto. Caso contrário, a operação é ignorada. 56 | * @param nova A forma a ser armazenada. 57 | */ 58 | public void addForma(FormaGeometrica nova) { 59 | if(quantidade 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 | /** Classe abstrata para representação de formas geomérticas */ 26 | public abstract class FormaGeometrica { 27 | private static int ultimoId=0; 28 | private String descricao; 29 | private int id; 30 | 31 | /** 32 | * Construtor protegido (só é usado pelas classes descendentes) 33 | * @param desc A descrição da forma geométrica. Não faz validação da descrição 34 | */ 35 | protected FormaGeometrica(String desc){ 36 | this.descricao = desc; 37 | this.id = ultimoId++; 38 | } 39 | 40 | public void setId(int id){ 41 | this.id = id; 42 | } 43 | /** 44 | * Retorna a área da forma geométrica. 45 | * @return Double com a área da forma geométrica instanciada 46 | */ 47 | public abstract double area(); 48 | 49 | /** 50 | * Retorna o perímetro da forma geométrica. 51 | * @return Double com o perímetro da forma geométrica instanciada 52 | */ 53 | public abstract double perimetro(); 54 | 55 | 56 | /** 57 | * "Nome" da forma geométrica: sua descrição simples, sem as medidas 58 | * @return String com o nome/tipo da forma 59 | */ 60 | public String nome(){ 61 | return descricao; 62 | } 63 | 64 | /** 65 | * Representação em string da forma: descrição e área. 66 | * @return String com a descrição e a área da forma instanciada. 67 | */ 68 | @Override 69 | public String toString(){ 70 | return String.format("%20s | Área: %05.2f | Perímetro: %05.2f", descricao, area(), perimetro()); 71 | } 72 | 73 | /** 74 | * Igualdade da forma geométrica: mesma descrição e mesma área. Causa erro se o parâmetro de comparação não for uma Forma. 75 | * @param obj A forma a ser comparada com esta. Causa erro se o parâmetro de comparação não for uma Forma. 76 | * @return boolean TRUE se ambas têm mesma descrição e área, FALSE caso contário. 77 | */ 78 | @Override 79 | public boolean equals(Object obj){ 80 | FormaGeometrica outra = (FormaGeometrica)obj; 81 | return ( this.descricao.equals(outra.descricao) && 82 | this.area() == outra.area() 83 | ); 84 | // return this.id == outra.id; 85 | } 86 | 87 | @Override 88 | public int hashCode(){ 89 | return id; 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/01_FormasGeometricas/src/FormasCollectionStream.java: -------------------------------------------------------------------------------- 1 | import java.nio.charset.Charset; 2 | import java.util.Collection; 3 | import java.util.Comparator; 4 | import java.util.HashMap; 5 | import java.util.LinkedList; 6 | import java.util.Random; 7 | import java.util.Scanner; 8 | import java.util.TreeMap; 9 | 10 | 11 | /** 12 | * MIT License 13 | * 14 | * Copyright(c) 2023-4 João Caram 15 | * 16 | * Permission is hereby granted, free of charge, to any person obtaining a copy 17 | * of this software and associated documentation files (the "Software"), to deal 18 | * in the Software without restriction, including without limitation the rights 19 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 20 | * copies of the Software, and to permit persons to whom the Software is 21 | * furnished to do so, subject to the following conditions: 22 | * 23 | * The above copyright notice and this permission notice shall be included in all 24 | * copies or substantial portions of the Software. 25 | * 26 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 27 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 28 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 29 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 30 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 31 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 32 | * SOFTWARE. 33 | */ 34 | 35 | /** 36 | * Para demonstração simples do uso de coleções (JCF), mapas e fluxos de dados 37 | * (streams) 38 | */ 39 | public class FormasCollectionStream { 40 | static Scanner teclado = new Scanner(System.in, Charset.forName("UTF-8")); 41 | 42 | static void limparTela() { 43 | System.out.print("\033[H\033[2J"); 44 | System.out.flush(); 45 | } 46 | 47 | static void pausa() { 48 | System.out.println("Tecle Enter para continuar."); 49 | teclado.nextLine(); 50 | } 51 | 52 | static int menuPrincipal() { 53 | limparTela(); 54 | String linha = "========================="; 55 | System.out.println("MUITAS FORMAS GEOMÉTRICAS"); 56 | System.out.println(linha); 57 | System.out.println("CRIAR / LISTAR / LOCALIZAR"); 58 | System.out.println("1 - Criar novo conjunto"); 59 | System.out.println("2 - Adicionar forma fixa"); 60 | System.out.println("3 - Mostrar conjunto"); 61 | System.out.println("4 - Pegar elemento"); 62 | System.out.println(linha); 63 | System.out.println("FILTROS"); 64 | System.out.println("5 - Filtrar formas por área"); 65 | System.out.println("6 - Nomes e áreas com filtro por área"); 66 | System.out.println("7 - Filtro por tamanho e tipo da forma"); 67 | System.out.println("8 - Formas distintas por área mínima por tamanho e tipo da forma"); 68 | System.out.println(linha); 69 | System.out.println("TOTALIZADORES"); 70 | System.out.println("9 - Maior forma em área"); 71 | System.out.println("10 - Menor forma em perímetro"); 72 | System.out.println("11 - Soma das áreas"); 73 | System.out.println("12 - Soma e média dos perímetros"); 74 | System.out.println("13 - Média dos perímetros de um tipo"); 75 | System.out.println(linha); 76 | System.out.println("MAP / REDUCE "); 77 | System.out.println("14 - Mostrar conjunto ordenado "); 78 | System.out.println("15 - Mostrar subconjunto ordenado por área"); 79 | System.out.println(linha); 80 | 81 | System.out.println("0 - Sair"); 82 | System.out.print("\nOpção: "); 83 | return Integer.parseInt(teclado.nextLine()); 84 | } 85 | 86 | /** 87 | * Cria um conjunto aleatório de formas geométricas. Para propósito de testes, 88 | * estamos usando um gerador aleatório de semente fixa. 89 | * 90 | * @param tamanho Tamanho do conjunto a ser criado. 91 | * @return Uma Collection aleatório com a quantidade de figuras especificadas em 92 | * "tamanho" 93 | */ 94 | public static Collection criaFormasAleatorias(final int tamanho, 95 | final Collection colecao) { 96 | Random sorteio = new Random(42); 97 | 98 | for (int i = 0; i < tamanho; i++) { 99 | int tipo = 1 + sorteio.nextInt(4); 100 | double dimensao1 = sorteio.nextDouble(2, 10); 101 | double dimensao2 = sorteio.nextDouble(2, 10); 102 | FormaGeometrica nova = null; 103 | switch (tipo) { 104 | case 1 -> nova = new Quadrado(dimensao1); 105 | case 2 -> nova = new Circulo(dimensao1); 106 | case 3 -> nova = new Retangulo(dimensao1, dimensao2); 107 | case 4 -> nova = new TrianguloRetangulo(dimensao1, dimensao2); 108 | } 109 | colecao.add(nova); 110 | } 111 | 112 | return colecao; 113 | 114 | } 115 | 116 | public static Collection criarNovoConjunto(final Collection colecao) { 117 | System.out.print("Qual o tamanho do conjunto a ser criado? "); 118 | int tamanho = Integer.parseInt(teclado.nextLine()); 119 | return criaFormasAleatorias(tamanho, colecao); 120 | 121 | } 122 | 123 | public static void main(final String[] args) { 124 | Comparator compArea = (f1, f2) -> f1.area() > f2.area() ? 1 : -1; 125 | Comparator compDesc = (f1, f2) -> f1.toString().compareTo(f2.toString()); 126 | 127 | LinkedList listaFormas = new LinkedList<>(); 128 | TreeMap arvore = new TreeMap<>(); 129 | HashMap hashFiguras = new HashMap<>(); 130 | int opcao; 131 | 132 | // meuConjuntoGeometrico = new LinkedList<>(criaFormasAleatorias(10, 133 | // meuConjuntoGeometrico)); 134 | 135 | opcao = menuPrincipal(); 136 | 137 | while (opcao != 0) { 138 | limparTela(); 139 | System.out.println(); 140 | switch (opcao) { 141 | case 1 -> { 142 | int tamanho; 143 | System.out.print("Qual o tamanho do conjunto? "); 144 | tamanho = Integer.parseInt(teclado.nextLine()); 145 | listaFormas.clear(); 146 | listaFormas = new LinkedList<>(criaFormasAleatorias(tamanho, listaFormas)); 147 | for (FormaGeometrica formaGeometrica : listaFormas) { 148 | hashFiguras.put(formaGeometrica.hashCode(), formaGeometrica); 149 | arvore.put(formaGeometrica.perimetro(), formaGeometrica); 150 | } 151 | 152 | } 153 | case 2 -> { 154 | FormaGeometrica quadradinhoDe8 = new Quadrado(8); 155 | listaFormas.addFirst(quadradinhoDe8); 156 | listaFormas.addLast(quadradinhoDe8); 157 | listaFormas.add(listaFormas.size()/2, quadradinhoDe8); 158 | hashFiguras.put(quadradinhoDe8.hashCode(), quadradinhoDe8); 159 | arvore.put(quadradinhoDe8.perimetro(), quadradinhoDe8); 160 | } 161 | 162 | case 3 -> { 163 | limparTela(); 164 | final String linha = "---------------------------"; 165 | System.out.println("LISTA:"); 166 | for (FormaGeometrica formaGeometrica : listaFormas) { 167 | System.out.println(formaGeometrica); 168 | } 169 | pausa(); 170 | System.out.println(linha); 171 | System.out.println("HASH MAP:"); 172 | for (FormaGeometrica formaGeometrica : hashFiguras.values()) { 173 | System.out.println(formaGeometrica); 174 | } 175 | pausa(); 176 | System.out.println(linha); 177 | System.out.println("ÁRVORE:"); 178 | for (FormaGeometrica formaGeometrica : arvore.values()) { 179 | System.out.println(formaGeometrica); 180 | } 181 | } 182 | case 4 -> { 183 | System.out.print("Identificador/posição do elemento: "); 184 | int idElemento = Integer.parseInt(teclado.nextLine()); 185 | FormaGeometrica f = hashFiguras.get(idElemento); 186 | System.out.println("Por id no mapa: "+f); 187 | f = listaFormas.get(idElemento); 188 | System.out.println("Por posição na lista: "+f); 189 | } 190 | case 5 -> { 191 | System.out.print("Qual é a área mínima do filtro? "); 192 | double areaMinima = Double.parseDouble(teclado.nextLine()); 193 | 194 | listaFormas.stream() 195 | .filter(f -> f.area() >= areaMinima) 196 | .forEach(f -> System.out.println(f)); 197 | 198 | } 199 | case 6 -> { 200 | System.out.print("Qual é a área mínima do filtro? "); 201 | double areaMinima = Double.parseDouble(teclado.nextLine()); 202 | 203 | listaFormas.stream() 204 | .filter(f -> f.area() >= areaMinima) 205 | .map(f -> new Object(){public double area = f.area(); public String nome = f.nome(); }) 206 | .forEach(o -> System.out.println(o.nome+" - Área "+o.area)); 207 | 208 | } 209 | case 7 -> { 210 | System.out.print("Qual é a área mínima do filtro? "); 211 | double areaMinima = Double.parseDouble(teclado.nextLine()); 212 | System.out.print("Qual o tipo da forma geométrica? "); 213 | String forma = teclado.nextLine().toLowerCase(); 214 | 215 | listaFormas.stream() 216 | .filter(f -> f.area() >= areaMinima) 217 | .filter(f -> f.nome().toLowerCase().equals(forma)) 218 | .forEach(f-> System.out.println(f)); 219 | 220 | } 221 | case 8 -> { 222 | System.out.print("Qual é a área mínima do filtro? "); 223 | double areaMinima = Double.parseDouble(teclado.nextLine()); 224 | System.out.println("Formas distintas:"); 225 | listaFormas.stream() 226 | .filter(f -> f.area() >= areaMinima) 227 | .map( f-> f.nome()) 228 | .distinct() 229 | .forEach(f-> System.out.println(f)); 230 | } 231 | case 9 ->{ 232 | System.out.println("Maior em área = " + 233 | listaFormas.stream() 234 | .max(compArea) 235 | .orElse(null) 236 | ); 237 | } 238 | case 10 ->{ 239 | System.out.println("Menor em perímetro = " + 240 | listaFormas.stream() 241 | .min((f1,f2) -> f1.perimetro() > f2.perimetro() ? 1: -1) 242 | .orElse(null) 243 | ); 244 | } 245 | case 11 -> { 246 | double somaAreas = listaFormas.stream() 247 | .mapToDouble(fg -> fg.area()) 248 | .sum(); 249 | System.out.println("Áreas somados: " + somaAreas); 250 | } 251 | case 12 -> { 252 | double somaPerimetros = listaFormas.stream() 253 | .mapToDouble(fg -> fg.perimetro()) 254 | .sum(); 255 | double mediaPerimetros = listaFormas.stream() 256 | .mapToDouble(fg -> fg.perimetro()) 257 | .average() 258 | .orElse(0d); 259 | System.out.println("Média dos perímetros: " + mediaPerimetros + " (soma de "+ somaPerimetros+")."); 260 | 261 | //dica: olhe o método .summaryStatistics() para a stream 262 | } 263 | 264 | case 13 -> { 265 | System.out.print("Qual o tipo da forma geométrica? "); 266 | String forma = teclado.nextLine().toLowerCase(); 267 | System.out.println("Média dos perímetros dos "+forma+"s = "+ 268 | listaFormas.stream() 269 | .filter(f -> f.nome().toLowerCase().equals(forma)) 270 | .mapToDouble(fg -> fg.perimetro()) 271 | .average() 272 | .orElse(0) 273 | ); 274 | 275 | } 276 | 277 | case 14 -> { 278 | System.out.print("Ordem de área (1) ou alfabética (2) ? "); 279 | int escolha = Integer.parseInt(teclado.nextLine()); 280 | Comparator compEscolhido = escolha==1 ? compArea : compDesc; 281 | 282 | System.out.println( 283 | listaFormas.stream() 284 | .sorted(compEscolhido) 285 | .map(Object::toString) 286 | .reduce((f1, f2) -> f1.concat("\n" + f2)) 287 | .orElse("Vazio") 288 | ); 289 | } 290 | case 15 -> { 291 | System.out.print("Qual o tipo da forma geométrica? "); 292 | String forma = teclado.nextLine().toLowerCase(); 293 | 294 | System.out.println( 295 | listaFormas.stream() 296 | .filter(f -> f.nome().toLowerCase().equals(forma)) 297 | .sorted(compArea) 298 | .map(Object::toString) 299 | .reduce((f1, f2) -> f1.concat("\n" + f2)) 300 | .orElse("Vazio") 301 | ); 302 | } 303 | default -> opcao = 1; 304 | } 305 | pausa(); 306 | opcao = menuPrincipal(); 307 | } 308 | 309 | teclado.close(); 310 | } 311 | } 312 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/01_FormasGeometricas/src/FormasDemo.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * MIT License 5 | * 6 | * Copyright(c) 2023 João Caram 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | 28 | public class FormasDemo { 29 | static Scanner teclado = new Scanner(System.in); 30 | 31 | /** 32 | * Encapsula o processo de construção de um conjunto, fazendo leituras de teclado do usuário. 33 | * As formas geométricas estão sendo criadas com tamanho fixo. 34 | * Sugestão: melhorar para que seja aleatório ou para ler do usuário. 35 | * @param tamanho Tamanho do conjunto a ser criado. 36 | * @return Um ConjuntoGeométrico com a quantidade de figuras especificadas em "tamanho" 37 | */ 38 | public static ConjuntoGeometrico criaFormas(int tamanho){ 39 | 40 | ConjuntoGeometrico conjunto = new ConjuntoGeometrico(tamanho); 41 | 42 | for (int i = 0; i < tamanho; i++) { 43 | System.out.println("Escolha a forma: "); 44 | System.out.print("1 - Quadrado | "); 45 | System.out.print("2 - Círculo | "); 46 | System.out.print("3 - Retângulo | "); 47 | System.out.print("4 - Triângulo Retângulo | "); 48 | int opcao = Integer.parseInt(teclado.nextLine()); 49 | FormaGeometrica nova = null; 50 | switch(opcao){ 51 | case 1-> nova = new Quadrado(4); 52 | case 2-> nova = new Circulo(4); 53 | case 3-> nova = new Retangulo(4, 2); 54 | case 4-> nova = new TrianguloRetangulo(4, 2); 55 | } 56 | conjunto.addForma(nova); 57 | } 58 | return conjunto; 59 | } 60 | public static void main(String[] args) { 61 | int tamanho; 62 | ConjuntoGeometrico meuConjuntoGeometrico; 63 | int opcao=-1; 64 | 65 | System.out.print("Qual o tamanho do conjunto a ser criado? "); 66 | tamanho = Integer.parseInt(teclado.nextLine()); 67 | meuConjuntoGeometrico = criaFormas(tamanho); 68 | 69 | while(opcao!=0){ 70 | System.out.println("1 - Mostrar conjunto"); 71 | System.out.println("2 - Maior forma"); 72 | System.out.println("3 - Criar novo conjunto"); 73 | System.out.println("0 - Sair"); 74 | System.out.print("Opção: "); 75 | opcao = Integer.parseInt(teclado.nextLine()); 76 | System.out.println("\n\n\n\n\n---------------------------"); 77 | switch(opcao){ 78 | case 1 ->{ 79 | System.out.println(meuConjuntoGeometrico); 80 | System.out.println("---------------------------"); 81 | teclado.nextLine(); 82 | } 83 | case 2 ->{ 84 | System.out.println(meuConjuntoGeometrico.maiorArea()); 85 | System.out.println("---------------------------"); 86 | teclado.nextLine(); 87 | } 88 | case 3 ->{ 89 | System.out.print("Qual o tamanho do conjunto a ser criado? "); 90 | tamanho = Integer.parseInt(teclado.nextLine()); 91 | meuConjuntoGeometrico = criaFormas(tamanho); 92 | } 93 | } 94 | } 95 | 96 | 97 | teclado.close(); 98 | } 99 | } 100 | 101 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/01_FormasGeometricas/src/PoligonoReto.java: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2023 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 | /** Classe abstrata para representação de polígonos retos (têm base e altura) */ 26 | public abstract class PoligonoReto extends FormaGeometrica{ 27 | 28 | protected double base; 29 | protected double altura; 30 | 31 | /** 32 | * Construtor protegido, usado apenas pelas classes descendentes. 33 | * Não faz validação de descrição, mas garante que base e altura serão pelo menos 1. 34 | * @param desc Descrição do polígono, sem validação. 35 | * @param base Base do parâmetro. Valor mínimo é 1. 36 | * @param altura Altura do parâmetro. Valor mínimo é 1. 37 | */ 38 | protected PoligonoReto(String desc, double base, double altura){ 39 | super(desc); 40 | this.base = base; 41 | this.altura = altura; 42 | if(this.base<=1d) this.base=1d; 43 | if(this.altura<=1d) this.altura=1d; 44 | } 45 | 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/01_FormasGeometricas/src/Quadrado.java: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2023 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 | /** Classe para representação de um Quadrado */ 26 | public class Quadrado extends PoligonoReto{ 27 | 28 | /** 29 | * Construtor: recebe um lado que será propagado para base e altura. A classe-mãe valida o lado como pelo menos 1. 30 | * @param lado Lado para o quadrado. Valor deve ser igual ou maior a 1, ou será corrigido para 1. 31 | */ 32 | public Quadrado(double lado){ 33 | super("QUADRADO", lado, lado); 34 | } 35 | 36 | /** 37 | * Calcula e retorna a área do quadrado 38 | * @return Área do quadrado (double) 39 | */ 40 | @Override 41 | public double area(){ 42 | return Math.pow(base,2); 43 | } 44 | 45 | /** 46 | * Calcula e retorna o perímetro do quadrado 47 | * @return Perímetro do quadrado (double) 48 | */ 49 | @Override 50 | public double perimetro(){ 51 | return this.base*4; 52 | } 53 | 54 | /** String do quadrado: inclui informação do tamanho da base 55 | * @return String contendo descrição, área, perímetro e base do quadrado 56 | */ 57 | @Override 58 | public String toString(){ 59 | return super.toString() + String.format(" | Base: %05.2f", base); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/01_FormasGeometricas/src/Retangulo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2023 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 | /** Classe para representar a forma Retângulo */ 26 | public class Retangulo extends PoligonoReto{ 27 | 28 | /** 29 | * Construtor: recebe base e altura. A classe-mãe valida ambos valores para o mínimo de 1 30 | * @param base Base para o retângulo. Valor deve ser igual ou maior a 1, ou será corrigido para 1. 31 | * @param altura Altura para o retângulo. Valor deve ser igual ou maior a 1, ou será corrigido para 1. 32 | */ 33 | public Retangulo(double base, double altura){ 34 | super("RETÂNGULO", base, altura); 35 | } 36 | 37 | /** 38 | * Calcula e retorna a área do retângulo 39 | * @return Área do retângulo (double) 40 | */ 41 | @Override 42 | public double area(){ 43 | return this.base * this.altura; 44 | } 45 | 46 | /** 47 | * Calcula e retorna o perímetro do retângulo 48 | * @return Perímetro do retângulo (double) 49 | */ 50 | @Override 51 | public double perimetro(){ 52 | return this.base*2 + 2*this.altura; 53 | } 54 | 55 | /** String do retângulo: inclui informação do tamanho da base e da altura 56 | * @return String contendo descrição, área, perímetro, base e altura do retângulo 57 | */ 58 | @Override 59 | public String toString(){ 60 | return super.toString() + String.format(" | Base: %05.2f | Altura: %05.2f", base, altura); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/01_FormasGeometricas/src/TrianguloRetangulo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2023 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 | /** Representação de uma forma Triângulo Retângulo */ 26 | public class TrianguloRetangulo extends PoligonoReto{ 27 | 28 | /** 29 | * Construtor: recebe os catetos. A classe-mãe valida ambos valores para o mínimo de 1 30 | * @param cateto1 Cateto para o triângulo. Valor deve ser igual ou maior a 1, ou será corrigido para 1. 31 | * @param cateto2 Cateto para o triângulo. Valor deve ser igual ou maior a 1, ou será corrigido para 1. 32 | */ 33 | public TrianguloRetangulo(double cateto1, double cateto2){ 34 | super("TRIANGULO RETÂNGULO", cateto1, cateto2); 35 | } 36 | 37 | /** 38 | * Calcula e retorna a área do triângulo 39 | * @return Área do triângulo (double) 40 | */ 41 | @Override 42 | public double area(){ 43 | return (this.base * this.altura)/2; 44 | } 45 | 46 | /** 47 | * Calcula e retorna o perímetro do triângulo 48 | * @return Perímetro do triângulo (double) 49 | */ 50 | @Override 51 | public double perimetro(){ 52 | return this.base + this.altura + hipotenusa(); 53 | } 54 | 55 | /** 56 | * Método interno. Calcula a hipotenusa para cálculo do perímetro. 57 | * @return Hipotenusa do triângulo (double) 58 | */ 59 | private double hipotenusa(){ 60 | double soma = Math.pow(altura, 2) + Math.pow(base, 2); 61 | return Math.sqrt(soma); 62 | } 63 | 64 | /** String do triângulo retângulo: inclui informação dos catetos (base e altura) e da hipotenusa 65 | * @return String contendo descrição, área, perímetro, catetos e hipotenusa do retângulo 66 | */ 67 | @Override 68 | public String toString(){ 69 | return super.toString() + String.format(" | Catetos: %05.2f e %05.2f | Hipotenusa: %05.2f", base, altura, hipotenusa()); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/02_Interfaces_Amplexa/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.project.sourcePaths": [ 3 | "src/Amplexa", 4 | "src" 5 | ], 6 | "java.project.outputPath": "bin", 7 | "java.project.referencedLibraries": [ 8 | "lib/**/*.jar" 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/02_Interfaces_Amplexa/README.md: -------------------------------------------------------------------------------- 1 | ## Interfaces e múltiplas habilidades 2 | 3 | Exemplo de uso de interface para conferir mútiplas habilidades a um conjunto de classes. 4 | 5 | `Amplexa` é uma assistente virtual que pode controlar `Dispositivos`. Alguns dispositivos podem ser `Desligáveis` por meio de um interruptor, outros podem ser `Reguláveis`, alterando sua potência e outros podem combinar as duas características. -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/02_Interfaces_Amplexa/src/Amplexa.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | /** 4 | * MIT License 5 | * 6 | * Copyright(c) 2024 João Caram 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | 28 | /** 29 | * Amplexa: assistente virtual que controla dispositivos com habilidades diversas. 30 | */ 31 | public class Amplexa { 32 | 33 | //#region atributos 34 | private String nome; 35 | private HashMap dispositivos; 36 | //#endregion 37 | 38 | /** 39 | * Cria uma assistente virtual com o nome designado (não validado.) 40 | * @param nome 41 | */ 42 | public Amplexa(String nome){ 43 | if(nome.length()<=0) nome = "Amplexa"; 44 | this.nome = nome; 45 | dispositivos = new HashMap<>(); 46 | } 47 | 48 | /** 49 | * Adiciona um dispositivo a ser controlado pela assistente. 50 | * @param novo O dispositivo a ser controlado. Caso tenha o mesmo nome de outro, o anterior será substituído. 51 | */ 52 | public void addDispositivo(Dispositivo novo) { 53 | dispositivos.put(novo.getNome(), novo); 54 | } 55 | 56 | /** 57 | * Liga um dispositivo por seu nome. Método ainda desprotegido, podendo causar exceção se um dispositivo não for desligável. 58 | * @param nome Nome do dispositivo. 59 | * @return TRUE/FALSE com o estado do dispositivo 60 | */ 61 | public boolean ligar(String nome) { 62 | IDesligavel disp = (IDesligavel)dispositivos.get(nome); 63 | boolean retorno = false; 64 | if(disp!=null) 65 | retorno = disp.ligar(); 66 | return retorno; 67 | } 68 | 69 | /** 70 | * Desliga um dispositivo por seu nome. Método ainda desprotegido, podendo causar exceção se um dispositivo não for desligável. 71 | * @param nome Nome do dispositivo. 72 | * @return TRUE/FALSE com o estado do dispositivo 73 | */ 74 | public boolean desligar(String nome) { 75 | IDesligavel disp = (IDesligavel)dispositivos.get(nome); 76 | boolean retorno = false; 77 | if(disp!=null) 78 | retorno = disp.desligar(); 79 | return retorno; 80 | } 81 | 82 | /** 83 | * Regula a potência de um dispositivo por seu nome. Método ainda desprotegido, podendo causar exceção se um dispositivo não for regulável. 84 | * @param nome Nome do dispositivo. 85 | */ 86 | public void regular(String nome, int potencia) { 87 | IRegulavel disp = (IRegulavel)dispositivos.get(nome); 88 | 89 | if(disp!=null) 90 | disp.regular(potencia); 91 | } 92 | 93 | /** 94 | * Relatório da assistente: lista todos os dispositivos e seus estados. 95 | * @return String com os dispositivos, um por linha, e seus estados. 96 | */ 97 | @Override 98 | public String toString(){ 99 | StringBuilder relat = new StringBuilder(nome+" controlando os dispositivos: \n"); 100 | for (Dispositivo disp : dispositivos.values()) { 101 | relat.append(disp+"\n"); 102 | } 103 | return relat.toString(); 104 | } 105 | 106 | } 107 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/02_Interfaces_Amplexa/src/App.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * MIT License 5 | * 6 | * Copyright(c) 2024 João Caram 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | /** 28 | * App-demo do uso de interfaces e habilidades combinadas. 29 | */ 30 | public class App { 31 | static int numero=1; //para id dos dispositivos 32 | static Scanner teclado; //para leitura do teclado 33 | 34 | /** 35 | * Cria um dispositivo baseado em uma string descritora. (método análogo a uma fábrica) 36 | * @param qual Qual dispositivo deve ser criado 37 | * @return Um dispositivo, ou nulo, em caso de string não reconhecida 38 | */ 39 | public static Dispositivo criarDispositivo(String qual){ 40 | Dispositivo novo = null; 41 | switch (qual.toLowerCase()) { 42 | case "lampada" -> novo = new Lampada("L"+numero); 43 | case "cafeteira" -> novo = new Cafeteira("C"+numero); 44 | case "geladeira" -> novo = new Geladeira("G"+numero); 45 | } 46 | numero++; 47 | return novo; 48 | } 49 | 50 | 51 | public static void main(String[] args) throws Exception { 52 | teclado = new Scanner(System.in); 53 | Amplexa assistente = new Amplexa("Faz Tudo"); 54 | for (int i = 0; i < 6; i++) { 55 | Dispositivo lamp = criarDispositivo("lampada"); 56 | assistente.addDispositivo(lamp); 57 | } 58 | 59 | System.out.println("=====INICIO====="); 60 | System.out.println(assistente); 61 | teclado.nextLine(); 62 | 63 | System.out.println("=====LIGANDO DISPOSITIVOS====="); 64 | assistente.ligar("L5"); 65 | System.out.println(assistente); 66 | teclado.nextLine(); 67 | 68 | System.out.println("=====ADICIONANDO E LIGANDO CAFETEIRAS====="); 69 | assistente.addDispositivo(criarDispositivo("cafeteira")); 70 | assistente.addDispositivo(criarDispositivo("cafeteira")); 71 | assistente.ligar("C7"); 72 | System.out.println(assistente); 73 | teclado.nextLine(); 74 | 75 | System.out.println("=====ADICIONANDO GELADEIRA====="); 76 | assistente.addDispositivo(criarDispositivo("GELADEIRA")); 77 | 78 | System.out.println(assistente); 79 | teclado.nextLine(); 80 | 81 | System.out.println("=====REGULANDO CAFETEIRAS E GELADEIRAS====="); 82 | assistente.ligar("C8"); 83 | assistente.regular("G9", 77); 84 | assistente.regular("C8", 93); 85 | 86 | System.out.println(assistente); 87 | teclado.nextLine(); 88 | 89 | 90 | teclado.close(); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/02_Interfaces_Amplexa/src/Cafeteira.java: -------------------------------------------------------------------------------- 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 | /** 26 | * Cafeteira: um dispositivo desligável e regulável 27 | */ 28 | public class Cafeteira extends Dispositivo implements IDesligavel, IRegulavel{ 29 | 30 | private boolean ligado; 31 | private int potencia; 32 | 33 | /** 34 | * Cria uma cafeteira desligada, com o nome especificado. 35 | * @param nome Nome da cafeteira (não deve ser vazio) 36 | */ 37 | public Cafeteira(String nome) { 38 | super(nome); 39 | desligar(); 40 | } 41 | 42 | /** 43 | * Liga a cafeteira, regulando sua potência para 50. 44 | * @return TRUE/FALSE com o estado da cafeteira. 45 | */ 46 | @Override 47 | public boolean ligar() { 48 | regular(50); 49 | return ligado; 50 | } 51 | 52 | /** 53 | * Desliga a cafeteira. 54 | * @return TRUE/FALSE com o estado da cafeteira. 55 | */ 56 | @Override 57 | public boolean desligar() { 58 | ligado = false; 59 | setEstado("Cafeteira desligada."); 60 | return ligado; 61 | } 62 | 63 | /** 64 | * Regula a cafeteira. Se a potência for válida (1 a 100), liga a cafeteira. Caso contrário, não altera seu estado. 65 | * @param potencia A potência para regular, que deve ser entre 1 e 100. 66 | */ 67 | @Override 68 | public void regular(int potencia){ 69 | if(potencia>0 && potencia<=100){ 70 | ligado = true; 71 | this.potencia = potencia; 72 | setEstado("Cafeteira ligada com potência "+this.potencia); 73 | } 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/02_Interfaces_Amplexa/src/Dispositivo.java: -------------------------------------------------------------------------------- 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 | /** 26 | * Classe abstrata Dispositivo: um dispositivo identificável para ser controlado pela assistente virtual. 27 | */ 28 | public abstract class Dispositivo { 29 | 30 | private String nome; 31 | private String estado; 32 | 33 | 34 | /** 35 | * Construtor para uso das classes filhas. Se o nome for vazio, fica como "Dispositivo desconhecido". 36 | * @param nome O nome do dispositivo. 37 | */ 38 | protected Dispositivo(String nome){ 39 | if(nome.length()<1) nome = "Dispositivo desconhecido"; 40 | this.nome = nome; 41 | this.estado = this.nome; 42 | } 43 | 44 | /** 45 | * Muda o estado do dispositvo. Operação só permitida para as classes filhas. 46 | * @param estado Estado a ser armazenado no dispositivo. (string) 47 | */ 48 | protected void setEstado(String estado){ 49 | this.estado = estado; 50 | } 51 | 52 | /** 53 | * Retorna o nome do dispositivo, como seu identificador. 54 | * @return String com o nome do dispositivo. 55 | */ 56 | public String getNome(){ 57 | return nome; 58 | } 59 | 60 | /** 61 | * Relatório do dispositivo: nome e estado 62 | * @return String com nome e estado do dispositivo. 63 | */ 64 | @Override 65 | public String toString(){ 66 | return nome+": "+estado; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/02_Interfaces_Amplexa/src/Geladeira.java: -------------------------------------------------------------------------------- 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 | /** 26 | * Geladeira: um dispositivo regulável 27 | */ 28 | public class Geladeira extends Dispositivo implements IRegulavel{ 29 | 30 | private int potencia; 31 | 32 | /** 33 | * Cria uma Geladeira ligada em potência média 34 | * @param nome Nome da geladeira (não deve ser vazio) 35 | */ 36 | public Geladeira(String nome) { 37 | super(nome); 38 | regular(60); 39 | } 40 | 41 | /** 42 | * Regula a geladeira. Se a potência não for válida (1 a 100), ignora a operação 43 | * @param potencia A potência para regular, que deve ser entre 1 e 100. 44 | */ 45 | @Override 46 | public void regular(int potencia){ 47 | if(potencia>0 && potencia<=100){ 48 | this.potencia = potencia; 49 | setEstado("Geladeira ligada com potência "+this.potencia); 50 | } 51 | } 52 | 53 | } 54 | 55 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/02_Interfaces_Amplexa/src/IDesligavel.java: -------------------------------------------------------------------------------- 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 | /** 26 | * Interface especificando dispositivos que podem ser desligados com um interruptor 27 | */ 28 | public interface IDesligavel { 29 | 30 | /** 31 | * Deve desligar um dispositivo e ajustar seu estado, bem como sua descrição de estado. 32 | * @return TRUE/FALSE com o estado do dispositivo 33 | */ 34 | public boolean desligar(); 35 | 36 | /** 37 | * Deve ligar um dispositivo e ajustar seu estado, bem como sua descrição de estado. 38 | * @return TRUE/FALSE com o estado do dispositivo 39 | */ 40 | public boolean ligar(); 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/02_Interfaces_Amplexa/src/IRegulavel.java: -------------------------------------------------------------------------------- 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 | /** 26 | * Interface especificando dispositivos que podem ter sua potência regulada 27 | */ 28 | 29 | public interface IRegulavel { 30 | 31 | /** 32 | * Deve regular um dispositivo de acordo com suas regras de potência. 33 | * @param potencia Valor inteiro, maior que 0, indicando a potência desejada 34 | */ 35 | public void regular(int potencia); 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Codigo/02_Polimorfismo/02_Interfaces_Amplexa/src/Lampada.java: -------------------------------------------------------------------------------- 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 | /** 26 | * Interface especificando dispositivos que podem ter sua potência regulada 27 | */ 28 | 29 | public class Lampada extends Dispositivo implements IDesligavel { 30 | 31 | private boolean ligado; 32 | 33 | /** 34 | * Construtor da lâmpada, a qual é criada desligada. O nome não deve ser vazio 35 | * @param nome String como nome identificador da lâmpada. 36 | */ 37 | public Lampada(String nome) { 38 | super(nome); 39 | desligar(); 40 | } 41 | 42 | /** 43 | * Liga uma lâmpada e atualiza seu estado 44 | * @return TRUE/FALSE conforme o estado da lâmpada 45 | */ 46 | @Override 47 | public boolean ligar() { 48 | ligado = true; 49 | setEstado("Lâmpada acesa."); 50 | return ligado; 51 | } 52 | 53 | /** 54 | * Desliga uma lâmpada e atualiza seu estado 55 | * @return TRUE/FALSE conforme o estado da lâmpada 56 | */ 57 | @Override 58 | public boolean desligar() { 59 | ligado = false; 60 | setEstado("Lâmpada apagada."); 61 | return ligado; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /Codigo/XulambsPizza/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /Codigo/XulambsPizza/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.compile.nullAnalysis.mode": "disabled" 3 | } -------------------------------------------------------------------------------- /Codigo/XulambsPizza/README.md: -------------------------------------------------------------------------------- 1 | # Xulambs Pizza 2 | 3 | ## Versão 0.2 - A pizzaria e seus pedidos 4 | 5 | A pizzaria percebeu que é melhor agrupar as vendas de pizzas em pedidos. Foram levantados os requisitos: 6 | 7 | 1. Um pedido deve ter um identificador único. 8 | 1. Um pedido deve ter sua data armazenada. 9 | 1. Um pedido aceitará novos itens até que seja fechado. 10 | 1. O relatório de um pedido deve mostrar a descrição de cada uma das pizzas, detalhadamente, e o valor total do pedido. -------------------------------------------------------------------------------- /Codigo/XulambsPizza/docs/diagramas/00_Pizza.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/ProgramacaoModular/a4e75de62dfefb73e5ac7053106011d850b67bb3/Codigo/XulambsPizza/docs/diagramas/00_Pizza.png -------------------------------------------------------------------------------- /Codigo/XulambsPizza/docs/diagramas/01_Pedido.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joaocaram/ProgramacaoModular/a4e75de62dfefb73e5ac7053106011d850b67bb3/Codigo/XulambsPizza/docs/diagramas/01_Pedido.png -------------------------------------------------------------------------------- /Codigo/XulambsPizza/docs/requisitos.md: -------------------------------------------------------------------------------- 1 | # Xulambs Pizza 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. -------------------------------------------------------------------------------- /Codigo/XulambsPizza/src/Comida.java: -------------------------------------------------------------------------------- 1 | public class Comida implements IComida{ 2 | 3 | private IComida item; 4 | 5 | public Comida(EComida escolha) { 6 | switch (escolha) { 7 | case PIZZA -> item = new Pizza(); 8 | case SANDUICHE -> item = new Sanduiche(); 9 | } 10 | } 11 | 12 | public Comida(IComida escolha) { 13 | item = escolha; 14 | } 15 | 16 | @Override 17 | public int adicionarIngredientes(int quantos) { 18 | return item.adicionarIngredientes(quantos); 19 | } 20 | 21 | public String notaDeCompra() { 22 | return item.notaDeCompra(); 23 | 24 | } 25 | 26 | @Override 27 | public double valorFinal() { 28 | return item.valorFinal(); 29 | } 30 | 31 | @Override 32 | public double valorAdicionais() { 33 | return item.valorAdicionais(); 34 | } 35 | } 36 | 37 | 38 | -------------------------------------------------------------------------------- /Codigo/XulambsPizza/src/EComida.java: -------------------------------------------------------------------------------- 1 | public enum EComida { 2 | PIZZA(8,"Pizza", 29d, 5d), 3 | SANDUICHE(5,"Sanduíche", 15d, 3d); 4 | 5 | private int maxIngredientes; 6 | private String descricao; 7 | private double precoBase; 8 | private double valorAdicional; 9 | 10 | private EComida(int maxAdicionais, String desc, double base, double adicional){ 11 | maxIngredientes = maxAdicionais; 12 | descricao = desc; 13 | precoBase = base; 14 | valorAdicional = adicional; 15 | } 16 | 17 | /** 18 | * @return the maxIngredientes 19 | */ 20 | public int getMaxIngredientes() { 21 | return maxIngredientes; 22 | } 23 | 24 | /** 25 | * @return the descricao 26 | */ 27 | public String getDescricao() { 28 | return descricao; 29 | } 30 | 31 | /** 32 | * @return the precoBase 33 | */ 34 | public double getPrecoBase() { 35 | return precoBase; 36 | } 37 | 38 | /** 39 | * @return the valorAdicional 40 | */ 41 | public double getValorAdicional() { 42 | return valorAdicional; 43 | } 44 | 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Codigo/XulambsPizza/src/EDistancia.java: -------------------------------------------------------------------------------- 1 | public enum EDistancia { 2 | CURTA(4,0), 3 | MEDIA(8,5), 4 | LONGA(Double.MAX_VALUE,8); 5 | 6 | private double distanciaMax; 7 | private double valorTaxa; 8 | 9 | private EDistancia(double distancia, double taxa){ 10 | distanciaMax = distancia; 11 | valorTaxa = taxa; 12 | } 13 | 14 | public double valorTaxa(){ 15 | return valorTaxa; 16 | } 17 | 18 | public static EDistancia definirDistancia(double distancia){ 19 | EDistancia[] distancias = EDistancia.values(); 20 | int pos = 0; 21 | while ((distancia > distancias[pos].distanciaMax)){ 22 | pos++; 23 | } 24 | return distancias[pos]; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Codigo/XulambsPizza/src/EEstadoPedido.java: -------------------------------------------------------------------------------- 1 | public enum EEstadoPedido { 2 | ABERTO, 3 | EM_ENTREGA, 4 | FECHADO 5 | } 6 | -------------------------------------------------------------------------------- /Codigo/XulambsPizza/src/IComida.java: -------------------------------------------------------------------------------- 1 | public interface IComida { 2 | public double valorFinal(); 3 | public String notaDeCompra(); 4 | public int adicionarIngredientes(int quantos); 5 | public double valorAdicionais(); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /Codigo/XulambsPizza/src/Pedido.java: -------------------------------------------------------------------------------- 1 | import java.text.NumberFormat; 2 | import java.time.LocalDate; 3 | import java.time.format.DateTimeFormatter; 4 | 5 | /** 6 | * MIT License 7 | * 8 | * Copyright(c) 2024 João Caram 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in all 18 | * copies or substantial portions of the Software. 19 | * 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | * SOFTWARE. 27 | */ 28 | 29 | /** Classe Pedido: composição com classe Pizza. Um pedido pode conter diversas pizzas. Elas podem 30 | * ser adicionadas desde que o pedido esteja aberto. Um pedido tem um identificador único e armazena 31 | * sua data. Ele deve calcular o preço a ser pago por ele e emitir um relatório detalhando suas pizzas 32 | * e o valor a pagar. 33 | */ 34 | public abstract class Pedido { 35 | 36 | //#region static/constantes 37 | /** Para gerar o id incremental automático */ 38 | private static int ultimoPedido; 39 | //#endregion 40 | 41 | //#region atributos 42 | private LocalDate data; 43 | protected IComida[] comidas; 44 | private int idPedido; 45 | protected int quantComidas; 46 | protected EEstadoPedido estado; 47 | //#endregion 48 | 49 | protected abstract double valorTaxa(); 50 | protected abstract boolean podeAdicionar(); 51 | 52 | //#region construtores 53 | /** 54 | * Cria um pedido com a data de hoje. Identificador é gerado automaticamente a partir 55 | * do último identificador armazenado. 56 | */ 57 | protected Pedido(int maxComidas) { 58 | idPedido = ++ultimoPedido; 59 | comidas = new Comida[maxComidas]; 60 | quantComidas = 0; 61 | estado = EEstadoPedido.ABERTO; 62 | data = LocalDate.now(); 63 | } 64 | //#endregion 65 | 66 | 67 | 68 | /** 69 | * Adiciona uma pizza ao pedido, se for possível. Caso não seja, a operação é 70 | * ignorada. Retorna a quantidade de pizzas do pedido após a execução. 71 | * @param comida Pizza a ser adicionada 72 | * @return A quantidade de pizzas do pedido após a execução. 73 | */ 74 | public final int adicionar(IComida comida) { 75 | if(podeAdicionar()){ 76 | comidas[quantComidas] = comida; 77 | quantComidas++; 78 | } 79 | return quantComidas; 80 | } 81 | 82 | /** 83 | * Fecha um pedido, desde que ele contenha pelo menos 1 pizza. Caso esteja vazio, 84 | * a operação é ignorada. 85 | */ 86 | public void fecharPedido() { 87 | if(quantComidas>0) 88 | estado = EEstadoPedido.FECHADO; 89 | } 90 | 91 | 92 | protected double valorItens(){ 93 | double precoItens =0d; 94 | for (int i=0; i 0) 103 | */ 104 | 105 | public double precoAPagar() { 106 | return valorItens() + valorTaxa(); 107 | } 108 | 109 | /** 110 | * Cria um relatório para o pedido, contendo seu número, sua data (DD/MM/AAAA), detalhamento 111 | * de cada pizza e o preço final a ser pago. 112 | * @return String com os detalhes especificados:. 113 | *
114 | 	 * PEDIDO - NÚMERO - DD/MM/AAAA
115 | 	 * 01 - DESCRICAO DA PIZZA
116 | 	 * 02 - DESCRICAO DA PIZZA
117 | 	 * 03 - DESCRICAO DA PIZZA
118 | 	 * 
119 | 	 * TOTAL A PAGAR: R$ VALOR
120 | 	 * 
121 | */ 122 | @Override 123 | public String toString() { 124 | NumberFormat moeda = NumberFormat.getCurrencyInstance(); 125 | DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); 126 | StringBuilder relat = new StringBuilder("XULAMBS PIZZA - Pedido "); 127 | relat.append(String.format("%02d %s - %s\n", idPedido, estado.toString(), formatter.format(data))); 128 | relat.append("============================="); 129 | 130 | for (int i=0; i0) 23 | estado = EEstadoPedido.EM_ENTREGA; 24 | } 25 | 26 | public void entregarPedido(){ 27 | if(estado.equals(EEstadoPedido.EM_ENTREGA)) 28 | estado = EEstadoPedido.FECHADO; 29 | } 30 | 31 | @Override 32 | protected double valorTaxa(){ 33 | int pos = 0; 34 | while ((distanciaEntrega > DISTANCIAS[pos])){ 35 | pos++; 36 | } 37 | return TAXAS[pos]; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Codigo/XulambsPizza/src/PedidoEntregaTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.assertEquals; 2 | import static org.junit.Assert.assertTrue; 3 | 4 | import org.junit.jupiter.api.BeforeAll; 5 | import org.junit.jupiter.api.BeforeEach; 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class PedidoEntregaTest { 9 | 10 | static Pedido pedido; 11 | static Comida pizzaCom2Ingredientes; 12 | static Comida pizzaSemIngredientes; 13 | 14 | @BeforeAll 15 | static public void criarPizzas(){ 16 | pizzaCom2Ingredientes = new Comida(EComida.PIZZA); 17 | pizzaCom2Ingredientes.adicionarIngredientes(2); 18 | pizzaSemIngredientes = new Comida(EComida.PIZZA); 19 | } 20 | 21 | @BeforeEach 22 | public void setUp(){ 23 | pedido = new PedidoEntrega(5); 24 | } 25 | 26 | @Test 27 | public void adicionaPizzaCorretamente(){ 28 | assertEquals(1, pedido.adicionar(pizzaCom2Ingredientes)); 29 | } 30 | 31 | @Test 32 | public void naoAdicionaPizzaEmPedidoFechado(){ 33 | pedido.adicionar(pizzaCom2Ingredientes); 34 | pedido.fecharPedido(); 35 | assertEquals(1,pedido.adicionar(pizzaSemIngredientes)); 36 | } 37 | 38 | @Test 39 | public void naoAdicionaPizzaAcimaDoLimite(){ 40 | for(int i=0; i<6; i++) 41 | pedido.adicionar(new Comida(EComida.PIZZA)); 42 | assertEquals(6,pedido.adicionar(pizzaSemIngredientes)); 43 | } 44 | 45 | 46 | @Test 47 | public void calculaPrecoCorretamenteComTaxa(){ 48 | pedido.adicionar(pizzaSemIngredientes); 49 | assertEquals(34d, pedido.precoAPagar(), 0.01); 50 | } 51 | 52 | @Test 53 | public void calculaPrecoCorretamenteIsentoDeTaxa(){ 54 | pedido = new PedidoEntrega(2); 55 | pedido.adicionar(pizzaSemIngredientes); 56 | assertEquals(29d, pedido.precoAPagar(), 0.01); 57 | } 58 | 59 | @Test 60 | public void relatorioContemDetalhes(){ 61 | pedido.adicionar(pizzaCom2Ingredientes); 62 | pedido.adicionar(pizzaSemIngredientes); 63 | String relatorio = pedido.toString(); 64 | assertTrue(relatorio.contains("29,00")); 65 | assertTrue(relatorio.contains("39,00")); 66 | assertTrue(relatorio.contains("73,00")); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Codigo/XulambsPizza/src/PedidoLocal.java: -------------------------------------------------------------------------------- 1 | public class PedidoLocal extends Pedido{ 2 | /** Para criar um vetor de pizzas de tamanho grande */ 3 | private static final int MAX_PIZZAS = 100; 4 | 5 | private static final double TAXA_SERVICO = 0.1; 6 | private static final double PCT_DESCONTO = 0.5; 7 | private static final int PIZZAS_DESCONTO = 4; 8 | 9 | public PedidoLocal(){ 10 | super(MAX_PIZZAS); 11 | } 12 | 13 | /** 14 | * Verifica se uma pizza pode ser adicionada ao pedido, ou seja, se o pedido 15 | * está aberto e há espaço na memória. 16 | * @return TRUE se puder adicionar, FALSE caso contrário 17 | */ 18 | @Override 19 | protected boolean podeAdicionar() { 20 | return estado.equals(EEstadoPedido.ABERTO) && quantComidas < MAX_PIZZAS; 21 | } 22 | 23 | @Override 24 | protected double valorTaxa(){ 25 | return valorItens() * TAXA_SERVICO; 26 | } 27 | 28 | protected double descontoItens(){ 29 | double desconto = 0d; 30 | if(quantComidas >= PIZZAS_DESCONTO){ 31 | double menor = Double.MAX_VALUE; 32 | for(int i=0; i< quantComidas; i++) 33 | if(comidas[i].valorFinal() < menor) 34 | menor = comidas[i].valorFinal(); 35 | desconto = menor * (1-PCT_DESCONTO); 36 | } 37 | return desconto; 38 | } 39 | 40 | @Override 41 | public double precoAPagar(){ 42 | return valorItens() + valorTaxa() - descontoItens(); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Codigo/XulambsPizza/src/PedidoLocalTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.assertEquals; 2 | import static org.junit.Assert.assertTrue; 3 | 4 | import org.junit.jupiter.api.BeforeAll; 5 | import org.junit.jupiter.api.BeforeEach; 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class PedidoLocalTest { 9 | 10 | static Pedido pedido; 11 | static Comida pizzaCom2Ingredientes; 12 | static Comida pizzaSemIngredientes; 13 | 14 | @BeforeAll 15 | static public void criarPizzas(){ 16 | (pizzaCom2Ingredientes = new Comida(EComida.PIZZA)).adicionarIngredientes(2); 17 | pizzaSemIngredientes = new Comida(EComida.PIZZA); 18 | } 19 | 20 | @BeforeEach 21 | public void setUp(){ 22 | pedido = new PedidoLocal(); 23 | } 24 | 25 | @Test 26 | public void adicionaPizzaCorretamente(){ 27 | assertEquals(1, pedido.adicionar(pizzaCom2Ingredientes)); 28 | } 29 | 30 | @Test 31 | public void naoAdicionaPizzaEmPedidoFechado(){ 32 | pedido.adicionar(pizzaCom2Ingredientes); 33 | pedido.fecharPedido(); 34 | assertEquals(1,pedido.adicionar(pizzaSemIngredientes)); 35 | } 36 | 37 | @Test 38 | public void calculaPrecoCorretamente(){ 39 | pedido.adicionar(pizzaSemIngredientes); 40 | assertEquals(31.9d, pedido.precoAPagar(), 0.01); 41 | } 42 | 43 | @Test 44 | public void relatorioContemDetalhes(){ 45 | pedido.adicionar(pizzaCom2Ingredientes); 46 | pedido.adicionar(pizzaSemIngredientes); 47 | String relatorio = pedido.toString(); 48 | assertTrue(relatorio.contains("29,00")); 49 | assertTrue(relatorio.contains("39,00")); 50 | assertTrue(relatorio.contains("74,80")); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Codigo/XulambsPizza/src/Pizza.java: -------------------------------------------------------------------------------- 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 | import java.text.NumberFormat; 26 | 27 | /** 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. 28 | * A pizza deve emitir uma nota de compra com os seus detalhes. 29 | */ 30 | public class Pizza implements IComida{ 31 | 32 | private static final EComida tipo = EComida.PIZZA; 33 | private static final int ADIC_DESCONTO = 5; 34 | private static final double PCT_DESCONTO = 0.5; 35 | 36 | private int quantosAdicionais; 37 | 38 | /** 39 | * Construtor padrão. Cria uma pizza sem adicionais. 40 | */ 41 | public Pizza() { 42 | 43 | } 44 | 45 | /** 46 | * Cria uma pizza com a quantidade de adicionais pré-definida. Em caso de valor inválido, a pizza será criada sem adicionais. 47 | * @param quantosAdicionais Quantidade de adicionais (entre 0 e 8, limites inclusivos). 48 | */ 49 | public Pizza(int quantosAdicionais) { 50 | adicionarIngredientes(quantosAdicionais); 51 | } 52 | 53 | 54 | private double descontoAdicionais() { 55 | double desconto = 0d; 56 | int quantosComDesconto = quantosAdicionais - ADIC_DESCONTO; 57 | if(quantosComDesconto > 0) 58 | desconto = quantosComDesconto * tipo.getValorAdicional() * PCT_DESCONTO; 59 | return desconto; 60 | } 61 | 62 | /** 63 | * Retorna o valor final da pizza, incluindo seus adicionais. 64 | * @return Double com o valor final da pizza. 65 | */ 66 | @Override 67 | public double valorFinal() { 68 | return tipo.getPrecoBase() + valorAdicionais() - descontoAdicionais(); 69 | } 70 | 71 | /** 72 | * Nota simplificada de compra: descrição da pizza, dos ingredientes e do preço. 73 | * @return String no formato ", no valor de " 74 | */ 75 | @Override 76 | public String notaDeCompra() { 77 | NumberFormat moeda = NumberFormat.getCurrencyInstance(); 78 | 79 | StringBuilder nota = new StringBuilder(); 80 | nota.append(String.format("%s (%s) com %d ingredientes (%s)", 81 | tipo.getDescricao(), moeda.format(tipo.getPrecoBase()), 82 | quantosAdicionais, moeda.format(valorAdicionais()))); 83 | 84 | nota.append(String.format("\n\tDesconto: %s", moeda.format(descontoAdicionais()))); 85 | nota.append(String.format("\nVALOR A PAGAR: %s", moeda.format(valorFinal()))); 86 | return nota.toString(); 87 | } 88 | 89 | @Override 90 | public int adicionarIngredientes(int quantos) { 91 | if(quantosAdicionais+quantos < tipo.getMaxIngredientes()) 92 | quantosAdicionais += quantos; 93 | return quantosAdicionais; 94 | 95 | } 96 | 97 | @Override 98 | public double valorAdicionais() { 99 | return quantosAdicionais * tipo.getValorAdicional(); 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /Codigo/XulambsPizza/src/Sanduiche.java: -------------------------------------------------------------------------------- 1 | import java.text.NumberFormat; 2 | 3 | public class Sanduiche implements IComida { 4 | 5 | private static final EComida base = EComida.SANDUICHE; 6 | private static final double VALOR_COMBO = 5d; 7 | private boolean comboFritas; 8 | private int quantAdicionais; 9 | 10 | private void init(boolean combo, int quantidadeIngredientes){ 11 | comboFritas = combo; 12 | quantAdicionais = 0; 13 | adicionarIngredientes(quantidadeIngredientes); 14 | 15 | } 16 | public Sanduiche() { 17 | init(false, 0); 18 | } 19 | 20 | public Sanduiche(int quantosAdicionais) { 21 | init(false, quantosAdicionais); 22 | } 23 | 24 | public Sanduiche(boolean combo) { 25 | init(combo, 0); 26 | } 27 | 28 | public Sanduiche(int quantosAdicionais, boolean combo) { 29 | init(combo, quantosAdicionais); 30 | } 31 | 32 | @Override 33 | public String notaDeCompra() { 34 | NumberFormat moeda = NumberFormat.getCurrencyInstance(); 35 | StringBuilder nota = new StringBuilder(); 36 | nota.append(String.format("%s (%s) com %d ingredientes (%s)", 37 | base.getDescricao(), moeda.format(base.getPrecoBase()), 38 | quantAdicionais, moeda.format(valorAdicionais()))); 39 | 40 | if(comboFritas) 41 | nota.append(String.format("\n\tCombo com fritas: %s", moeda.format(VALOR_COMBO))); 42 | nota.append(String.format("\nVALOR A PAGAR: %s", moeda.format(valorFinal()))); 43 | return nota.toString(); 44 | } 45 | 46 | @Override 47 | public double valorFinal() { 48 | double valor = base.getPrecoBase() + valorAdicionais(); 49 | valor += (comboFritas)? VALOR_COMBO : 0; 50 | return valor; 51 | } 52 | @Override 53 | public int adicionarIngredientes(int quantos) { 54 | if ((quantAdicionais + quantos) < base.getMaxIngredientes()) 55 | quantAdicionais += quantos; 56 | return quantAdicionais; 57 | } 58 | @Override 59 | public double valorAdicionais() { 60 | return quantAdicionais * base.getValorAdicional(); 61 | } 62 | 63 | } 64 | 65 | -------------------------------------------------------------------------------- /Codigo/XulambsPizza/src/XulambsFoods.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.List; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * MIT License 7 | * 8 | * Copyright(c) 2022-24 João Caram 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in 18 | * all 19 | * copies or substantial portions of the Software. 20 | * 21 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 22 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 25 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 26 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 27 | * SOFTWARE. 28 | */ 29 | 30 | public class XulambsFoods { 31 | static Scanner teclado; 32 | 33 | static void limparTela() { 34 | System.out.print("\033[H\033[2J"); 35 | System.out.flush(); 36 | } 37 | 38 | static void pausa() { 39 | System.out.println("Tecle Enter para continuar."); 40 | teclado.nextLine(); 41 | } 42 | 43 | static void cabecalho() { 44 | limparTela(); 45 | System.out.println("XULAMBS FOODS - v0.3\n============="); 46 | } 47 | 48 | static int exibirMenu() { 49 | cabecalho(); 50 | 51 | System.out.println("1 - Abrir Pedido"); 52 | System.out.println("2 - Alterar Pedido"); 53 | System.out.println("3 - Relatório de Pedido"); 54 | System.out.println("4 - Encerrar Pedido"); 55 | System.out.println("0 - Finalizar"); 56 | System.out.print("Digite sua escolha: "); 57 | 58 | return Integer.parseInt(teclado.nextLine()); 59 | } 60 | 61 | static Pedido criarPedidoEntrega(){ 62 | System.out.print("\nDistância para entrega: "); 63 | double distancia = Double.parseDouble(teclado.nextLine()); 64 | return new PedidoEntrega(distancia); 65 | } 66 | static Pedido escolherTipoPedido(){ 67 | Pedido novo = null; 68 | cabecalho(); 69 | int escolha; 70 | System.out.println("Escolha o tipo de pedido:"); 71 | System.out.println("1 - Local"); 72 | System.out.println("2 - Para entrega"); 73 | System.out.print("Sua opção: "); 74 | escolha = Integer.parseInt(teclado.nextLine()); 75 | switch (escolha) { 76 | case 1: novo = new PedidoLocal(); 77 | break; 78 | case 2: novo = criarPedidoEntrega(); 79 | break; 80 | } 81 | return novo; 82 | } 83 | static Pedido abrirPedido() { 84 | 85 | Pedido novoPedido = escolherTipoPedido(); 86 | System.out.println(novoPedido.toString()); 87 | pausa(); 88 | adicionarComidas(novoPedido); 89 | return novoPedido; 90 | } 91 | 92 | static void relatorioPedido(Pedido pedido) { 93 | cabecalho(); 94 | System.out.println(pedido.toString() + "\n"); 95 | } 96 | 97 | static Pedido localizarPedido(List pedidos) { 98 | cabecalho(); 99 | int id; 100 | System.out.println("Localizando um pedido."); 101 | System.out.print("ID do pedido: "); 102 | id = Integer.parseInt(teclado.nextLine()); 103 | 104 | for (Pedido ped : pedidos) { 105 | if (ped.toString().contains("Pedido " + String.format("%02d", id))) 106 | return ped; 107 | } 108 | return null; 109 | } 110 | 111 | private static void adicionarComidas(Pedido procurado) { 112 | String escolha = "n"; 113 | do { 114 | relatorioPedido(procurado); 115 | IComida novaComida = comprarComida(); 116 | 117 | procurado.adicionar(novaComida); 118 | System.out.print("\nDeseja outra comida? (s/n) "); 119 | escolha = teclado.nextLine(); 120 | } while (escolha.toLowerCase().equals("s")); 121 | } 122 | 123 | private static IComida comprarComida() { 124 | IComida novaComida = null; 125 | int escolha = 0; 126 | System.out.println("Escolha sua comida: "); 127 | System.out.println("1 - Pizza"); 128 | System.out.println("2 - Sanduiche"); 129 | System.out.print("Opção: "); 130 | escolha = Integer.parseInt(teclado.nextLine()); 131 | switch (escolha) { 132 | case 1: novaComida = comprarPizza(); 133 | break; 134 | case 2: 135 | System.out.print("Sanduiche: Deseja combo com fritas? (s/n) "); 136 | String combo = teclado.nextLine(); 137 | boolean querCombo = combo.toLowerCase().equals("s")? true : false; 138 | novaComida = new Sanduiche(querCombo); 139 | break; 140 | } 141 | if(novaComida!=null){ 142 | escolherIngredientes(novaComida); 143 | mostrarNota(novaComida); 144 | } 145 | return novaComida; 146 | } 147 | 148 | static IComida comprarPizza() { 149 | System.out.println("Comprando uma nova pizza:"); 150 | Pizza novaPizza = new Pizza(); 151 | return novaPizza; 152 | } 153 | 154 | static void escolherIngredientes(IComida comida) { 155 | System.out.print("Quantos adicionais você deseja? (máx. 8): "); 156 | int adicionais = Integer.parseInt(teclado.nextLine()); 157 | comida.adicionarIngredientes(adicionais); 158 | } 159 | 160 | static void mostrarNota(IComida comida) { 161 | System.out.println("Você acabou de comprar: "); 162 | System.out.println(comida.notaDeCompra()); 163 | 164 | } 165 | 166 | public static void main(String[] args) throws Exception { 167 | teclado = new Scanner(System.in); 168 | Pedido pedido = null; 169 | List todosOsPedidos = new LinkedList<>(); 170 | int opcao; 171 | opcao = exibirMenu(); 172 | do { 173 | switch (opcao) { 174 | case 1: 175 | pedido = abrirPedido(); 176 | todosOsPedidos.add(pedido); 177 | relatorioPedido(pedido); 178 | break; 179 | case 2: 180 | pedido = localizarPedido(todosOsPedidos); 181 | if (pedido != null){ 182 | adicionarComidas(pedido); 183 | relatorioPedido(pedido); 184 | } 185 | else 186 | System.out.println("Pedido não existente."); 187 | break; 188 | case 3: 189 | pedido = localizarPedido(todosOsPedidos); 190 | if (pedido != null) 191 | relatorioPedido(pedido); 192 | else 193 | System.out.println("Pedido não existente."); 194 | break; 195 | case 4: 196 | pedido = localizarPedido(todosOsPedidos); 197 | if (pedido != null) { 198 | pedido.fecharPedido(); 199 | System.out.println("Pedido encerrado: "); 200 | System.out.println(pedido.toString()); 201 | } else 202 | System.out.println("Pedido não existente."); 203 | break; 204 | 205 | } 206 | pausa(); 207 | opcao = exibirMenu(); 208 | } while (opcao != 0); 209 | 210 | teclado.close(); 211 | System.out.println("FLW T+ VLW ABS."); 212 | } 213 | 214 | } 215 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | /** 2 | * MIT License 3 | * 4 | * Copyright(c) 2022-25 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 | */ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Programação Modular 2 | Conteúdo da disciplina de Programação Modular (teoria e laboratório) - Eng. Soft - PUC Minas Praça da Liberdade - noite - Semestre 1/2025. Última atualização: exemplos de Java Básico para a turma 1/2025. 3 | 4 | ## Código 5 | 6 | __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. 7 | --------------------------------------------------------------------------------