Handling of HashMap between classes (Interpretation and Application)

5

It's my first question, sorry for the extension, I'm in the following exercise:

  

Create a Pizza class that has the methodIngredient () that   receives a String with the ingredient to be added. This class   you must also have the getPreco () method that computes as follows:   2 ingredients or less cost 15 reais, 3 to 5 ingredients cost   20 reais and more than 5 ingredients costs 23 reais.

     

You must account for the ingredients you spend for all the pizzas!   Use a static variable in the Pizza class to save this type   information (hint: use the HashMap class to save the   ingredient as key and an Integer as value). Create the method   static count () to be called inside   addIngredient () and make that record.

     

Create a new class called Shopping Cart that you can receive   objects in the Pizza class. It must have a method that returns the value   total of all the pizzas added. Cart can not accept that   add a pizza without ingredients.

     

Create a Main class with the main () method that does the following:

     
  • Create 3 pizzas with different ingredients;
  •   
  • Add these Pizzas to a Shopping Cart;
  •   
  • Print Cart Total;
  •   
  • Print the amount of each ingredient used.
  •   

I am having difficulty understanding what is requested, especially in relation to the listing of ingredients by HashMap, from what I understood in the Pizza class I will create the methods requested in the exercise, and in the additionIngredients () I will receive ingredient to ingredient and account by countingIngredient () the amount of ingredients of each pizza and send to getPreco ().

Having the individual value, I will send the pizza object to the Shopping Cart class, which will validate whether the pizza has ingredients or not, if yes, will add up to the total value. In main class I will add the pizzas and ingredients of each, and display the total value and quantity of each ingredient, correct?

Complementing, in HashMap how will this be passed and counted in the Pizza class, since it works with the Key and Value only and seems to be of type Integer? How is this data handled for separate variables? If anyone can give me a similar example with the handling between classes I am very grateful, because I did not find anything similar on the internet, only examples related to class main (). So far I've done this:

        public class Pizza {

        static int ingredienteTotal = 0;
        public String ingrediente;
        public int quantidadeContador;
        public int preco = 0;


        static int contabilizaIngrediente(int quantidade){
            ingredienteTotal += quantidade;

            return ingredienteTotal;            
        }

        public String adicionaIngrediente(String ingrediente) {
            contabilizaIngrediente(quantidadeContador++);
            this.ingrediente += ingrediente;
            return ingrediente;
        }

        public int getPreco(){
            if (contabilizaIngrediente(quantidadeContador)<= 2){
                 preco = 15;
                }
            else if (contabilizaIngrediente(quantidadeContador)>= 3 
                    & (contabilizaIngrediente(quantidadeContador)<= 5)) {
                 preco = 20;
                }

            else if (contabilizaIngrediente(quantidadeContador)< 5){
                 preco = 23;
        }
            return preco;
        }

        public void imprimeQuantidadeIngrediente(){
            // aqui teria que imprimir qual ingrediente e sua quantidade individual, mas nao sei como fazer
        }
    }

public class CarrinhoCompras {

    int precoTotal;

    public void adicionaPizzas (Pizza p){
        //validando se há ingredientes
        if (p.quantidadeContador != 0)

            this.precoTotal += p.getPreco();
        else

            System.out.println("Pizza sem ingredientes");

    }
    //imprime o preço de todas as pizzas    
    public void imprimeTotal(){
        System.out.println("O preço total é: " + precoTotal);

    }


}

import java.util.HashMap;


public class Principal {

    public static void main(String[] args) {
        //instanciando uma lista de ingredientes
        HashMap <String, Integer> ingrediente =  new HashMap<String, Integer>();
        //preenchendo a lista
        ingrediente.put("manjericão", 2);
        ingrediente.put("queijo", 3);
        ingrediente.put("tomate", 2);
        //criando uma nova pizza
        Pizza p1 = new Pizza();
        //tentando inserir o ingrediente por String, mas o método identifica como Integer
        p1.adicionaIngrediente(ingrediente.get("manjericao"));


}
}
    
asked by anonymous 13.01.2017 / 03:34

1 answer

2

A possible response

Below is a code for you to use as a basis for your exercise. Ideally, you look at the code, understand each part, and then make zero from your understanding. The most complex part is to use the HashMap class, however through the Java documentation you can understand how this collection works.

The statement is not complete. He leaves confused what one really wants in response. It is best for you to talk to those who have passed the exercise to better understand the issue and adapt the code accordingly.

import java.util.*;

class Pizza
{
    private HashMap<String, Integer> ingredientes = new HashMap<String, Integer>();

    public void adicionarIngrediente(String ingrediente, Integer qtde)
    {
            // nao verifica se o mesmo ingrediente ja foi adicionado e vai substituir nesse caso
            ingredientes.put(ingrediente, qtde);
    }

        // descobre se a pizza esta sem ingredientes
    public int getQtdeIngredientes() {
            return ingredientes.size(); 
    }

        // calcula o preco da pizza conforme a regra de qtde de ingredientes
    public int getPreco()
    {
            Integer total = 0;

            for (Integer value : ingredientes.values()) {
                Integer preco = 0;
                if (value <= 2) {
                        preco = 15;
                } else if (value <= 5) {
                        preco = 20;
                } else {
                        preco = 23;
                }
                total += preco;
            }

            return total;

    }

        // retorna os ingredientes para que possa fazer a soma dos ingredientes de todas as pizzas
        public HashMap<String, Integer> getIngredientes()
        {
            return ingredientes;
        }
}

class CarrinhoDeCompras 
{
        // lista de pizzas que foram adicionadas no carrinho
    private List<Pizza> pizzas = new ArrayList<Pizza>();

    public void adicionaPizza(Pizza pizza) {
            if (pizza.getQtdeIngredientes() > 0) {
                pizzas.add(pizza);
            }

    }

        // calcula o preco total das pizzas do carrinho
    public Integer getTotalPreco() {
            Integer total = 0;
            for (Pizza item : pizzas) {
                total += item.getPreco();   
            }
            return total;
    }

        // contabiliza as quantidades de todos os ingredientes de todas as pizzas        
    public HashMap<String, Integer> getIngredientes() {
            HashMap<String, Integer> cesta = new HashMap<String, Integer>();
            for (Pizza item : pizzas) {
                HashMap<String, Integer> ingredientes = item.getIngredientes();
                for (String key : ingredientes.keySet()) {
                    Integer total = ingredientes.get(key);
                    if (cesta.containsKey(key)) {
                        total += cesta.get(key);
                    }
                    cesta.put(key, total);
                }
            }

            return cesta;
    }

}

/**
 *
 * @author vagnerp
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Pizza muzzarela = new Pizza();
        muzzarela.adicionarIngrediente("Tomate", 1);
        muzzarela.adicionarIngrediente("Queijo", 3);
        muzzarela.adicionarIngrediente("Azeitona", 5);

        Pizza margerita = new Pizza();
        margerita.adicionarIngrediente("Tomate", 1);
        margerita.adicionarIngrediente("Queijo", 3);
        margerita.adicionarIngrediente("Manjericao", 2);
        margerita.adicionarIngrediente("Azeitona", 2);

        Pizza portugueza = new Pizza();
        portugueza.adicionarIngrediente("Tomate", 1);
        portugueza.adicionarIngrediente("Queijo", 2);
        portugueza.adicionarIngrediente("Ovo", 2);
        portugueza.adicionarIngrediente("Azeitona", 5);
        portugueza.adicionarIngrediente("Prezunto", 2);

        CarrinhoDeCompras carrinho = new CarrinhoDeCompras();
        carrinho.adicionaPizza(muzzarela);
        carrinho.adicionaPizza(margerita);
        carrinho.adicionaPizza(portugueza);

        System.out.println("Total do Preco do Carrinho: " + carrinho.getTotalPreco());
        System.out.println("");
        System.out.println("Qtde Ingredientes");
        System.out.println("=================");
        for(Map.Entry<String, Integer> entry : carrinho.getIngredientes().entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

    }

}
    
13.01.2017 / 12:54