Ybadoo - Soluções em Software Livre
Tutoriais
Programação Orientada a Objetos

(Deitel, 2003) Desenvolva um programa que reproduza o jogo adivinhe o número como segue: o programa escolhe um número para ser adivinhado selecionando um inteiro aleatório no intervalo de 1 a 1000. O programa apresenta a mensagem Adivinhe um número entre 1 e 1000. O jogador insere o palpite a ser analisado pelo programa. Se o palpite do jogador estiver incorreto, o programa deve exibir a mensagem Muito alto! Tente novamente! ou Muito baixo! Tente novamente! para auxiliar o jogador a se aproximar da resposta correta. Quando o usuário inserir a resposta correta, o programa deve apresentar a mensagem Parabéns! Você adivinhou o número!.

Desenvolva a solução solicitada, apresentando a modelagem do projeto em Unified Modeling Language (UML) e a sua implementação.

 

Diagrama de Classes na Linguagem de Programação Java Output.java TextOutput.java Input.java KeyboardInput.java GuessNumberGame.java Application.java
Diagrama de Classes
Diagrama de Classes na Linguagem de Programação Java

Arquivo Output.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial07.exercicio06;

/**
 * Definicao dos metodos de saida para o usuario
 */
public interface Output
{
  /**
   * Boas-vinda ao jogo
   */
  public void welcome();
  
  /**
   * Palpite do usuario
   */
  public void hint();
  
  /**
   * Palpite do usuario fora do intervalo 
   * 
   * @param minimum valor minimo aceitavel
   * @param maximum valor maximo aceitavel
   * @param hint palpite fornecido pelo usuario
   */
  public void hintError(int minimum, int maximum, int hint);
  
  /**
   * Palpite abaixo do numero a ser descoberto
   * 
   * @param hint palpite fornecido pelo usuario
   */
  public void smaller(int hint);
  
  /**
   * Palpite acima do numero a ser descoberto
   * 
   * @param hint palpite fornecido pelo usuario
   */
  public void greater(int hint);

  /**
   * Tentativas realizadas pelo usuario
   * 
   * @param attempt tentativas realizadas pelo usuairo
   */
  public void attempt(int attempt);
  
  /**
   * Finalizacao do jogo
   */
  public void finished();
}

Arquivo TextOutput.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial07.exercicio06;

/**
 * Saida para o usuario via modo texto
 */
public class TextOutput implements Output
{
  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial07.exercicio06.Output#welcome()
   */
  @Override
  public void welcome()
  {
    System.out.println("Adivinhe um número entre 1 e 1000");
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial07.exercicio06.Output#hint()
   */
  @Override
  public void hint()
  {
    System.out.print("Palpite: ");
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial07.exercicio06.Output#hintError(int, int, int)
   */
  @Override
  public void hintError(int minimum, int maximum, int hint)
  {
    System.err.println("O palpite deve estar entre " + minimum + " e " + maximum);
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial07.exercicio06.Output#smaller(int)
   */
  @Override
  public void smaller(int hint)
  {
    System.out.println("Muito baixo! Tente novamente!");
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial07.exercicio06.Output#greater(int)
   */
  @Override
  public void greater(int hint)
  {
    System.out.println("Muito alto! Tente novamente!");
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial07.exercicio06.Output#attempt(int)
   */
  @Override
  public void attempt(int attempt)
  {
    System.out.println("Tentativas realizadas: " + attempt);
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial07.exercicio06.Output#finished()
   */
  @Override
  public void finished()
  {
    System.out.println("Parabéns! Você adivinhou o número!");
  }
}

Arquivo Input.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial07.exercicio06;

/**
 * Definicao dos metodos de entrada do usuario
 */
public interface Input
{
  /**
   * Retornar o palpite do usuario
   * 
   * @param minimum valor minimo aceitavel
   * @param maximum valor maximo aceitavel
   * @return palpite do usuario
   */
  public int getHint(int minimum, int maximum);
  
  /**
   * Retornar a saida para o usuario
   * 
   * @return saida para o usuario
   */
  public Output getOutput();
}

Arquivo KeyboardInput.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial07.exercicio06;

import java.util.Scanner;

/**
 * Entrada do usuario via teclado
 */
public class KeyboardInput implements Input
{
  /**
   * Saida para o usuario
   */
  private Output output;
  
  /**
   * Acesso ao teclado
   */
  Scanner scanner;
  
  /**
   * Inicializar a entrada do usuario via teclado
   * 
   * @param output saida para o usuario
   */
  public KeyboardInput(Output output)
  {
    if(output != null)
    {
      this.output = output;
    }
    else
    {
      throw new IllegalArgumentException("The output argument is null");
    }
    
    scanner = new Scanner(System.in);
  }
  
  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial07.exercicio06.Input#getHint(int, int)
   */
  @Override
  public int getHint(int minimum, int maximum)
  {
    while(true)
    {
      output.hint();
      
      int hint = scanner.nextInt();
      
      if((hint < minimum) || (hint > maximum))
      {
        output.hintError(minimum, maximum, hint);
      }
      else
      {
        return hint;
      }
    }
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial07.exercicio06.Input#getOutput()
   */
  @Override
  public Output getOutput()
  {
    return output;
  }
}

Arquivo GuessNumberGame.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial07.exercicio06;

import java.util.Random;

/**
 * Jogo para adivinhar o numero
 */
public class GuessNumberGame
{
  /**
   * Valor minimo do conjunto a ser adivinhado
   */
  private final int MINIMUM = 1;
  
  /**
   * Valor maximo do conjunto a ser adivinhado
   */
  private final int MAXIMUM = 1000;
  
  /**
   * Entrada do usuario
   */
  private Input input;
  
  /**
   * Saida para o usuario
   */
  private Output output;
  
  /**
   * Gerador de numero aleatorios
   */
  private Random random;
  
  /**
   * Inicializar o jogo para adivinhar o numero
   * 
   * @param input entrada do usuario
   */
  public GuessNumberGame(Input input)
  {
    if(input != null)
    {
      this.input = input;
    }
    else
    {
      throw new IllegalArgumentException("The input argument is null");
    }

    output = input.getOutput();
    
    random = new Random();
  }
  
  /**
   * Executar o jogo
   */
  public void play()
  {
    output.welcome();
    
    int number = random.nextInt(MAXIMUM) + 1;
    
    int hint = input.getHint(MINIMUM, MAXIMUM);
    
    int attempt = 1;
    
    while(number != hint)
    {
      if(number < hint)
      {
        output.greater(hint);
      }
      else
      {
        output.smaller(hint);
      }
      
      hint = input.getHint(MINIMUM, MAXIMUM);
      
      attempt = attempt + 1;
    }

    output.finished();
    
    output.attempt(attempt);
  }
}

Arquivo Application.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial07.exercicio06;

/**
 * Classe responsavel pela execucao do jogo para adivinhar o numero
 */
public class Application
{
  /**
   * Construtor para inicializar a execucao da classe GuessNumberGame
   */
  private Application()
  {

  }

  /**
   * Metodo principal da linguagem de programacao Java
   *
   * @param args argumentos da linha de comando (nao utilizado)
   */
  public static void main(String[] args)
  {
    Output output = new TextOutput();
    
    Input input = new KeyboardInput(output);
    
    GuessNumberGame game = new GuessNumberGame(input);
    
    game.play();
  }
}

Deitel, H. M. (2003). Java, como programar. 4ª edição. Porto Alegre: Bookman. 1.386 páginas.