Hashmap manipulation between classes (Interpretation and Application)

Asked

Viewed 1,139 times

5

is my first question, sorry for the length, I am in doubt in the following exercise:

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

You need to count the ingredients spent by all the pizzas! Use a static variable in the Pizza class to store this type information (tip: use the Hashmap class to store the key ingredient and an Integer as value). Create the method Static accounts Gredient() to be called within additionIngrediente() and make this record.

Create a new class called Cartyou can receive Pizza class objects. It must have a method that returns the value total of all pizzas added. Cart cannot accept that a pizza with no ingredients is added.

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

  • Creates 3 pizzas with different ingredients;
  • Add these Pizzas to a Cartdecompose;
  • Prints the total of the Cartdecompress;
  • Prints the amount of each ingredient used.

I’m having a hard time understanding what is requested, especially regarding the listing of ingredients by Hashmap, so I understood in the Pizza class I will create the methods requested in the exercise, and in the addingIngredientes() I will receive ingredient by ingredient and count by countingIngrediente() the amount of ingredients of each pizza and send to getPreco().

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

Additionally, in Hashmap how will this be passed and accounted for in the Pizza class, since it works with Key and Value only and seems to be of the Integer type? How are these data manipulated for separate variables? If anyone can give me a similar example with class manipulation I really appreciate it, because I didn’t find anything like it on the Internet, only examples related to main() class. So far I’ve done it:

        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"));


}
}

1 answer

2


A possible answer

Below is a code for you to use base for your exercise. Ideally, you look at the code, understand each part, and then do it from scratch. The most complex part is using the class HashMap but through the Java documentation you can understand how this collection works.

The statement is not complete. It confuses what is really desired as an answer. The best thing is to talk to the people who 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());
        }

    }

}
  • This logic helped me a lot, so I had seen in other exercises the Hashmap was only used in main(), I believed that this was the pattern, a doubt, because in the comparisons you are using Integer and not int? I switched here and there was no mistake so far.

  • @Paolafarias The Hashmap is a way to solve and I think the idea of exercise and give the opportunity to know this class. "Integer" is a class and "int" is a primitive type. Using the class instead of a primitive has some advantages like being able to associate a null, serialize, parse strings, etc. In the case of this exercise there are no such needs, so I think using the int will work without problems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.