Constructor with a String and a String array is not working

3

I created these lines of code in a Java exercise ...

public class Pizza {
    ...
    public Pizza (String nomeDestaPizza, String[] arrayIngredientes) {
        ...
    }
}

public static void main(String[] args) {
    ...
    Pizza pizza1 = new Pizza("americana", "molho de tomate", "mussarela", "presunto", "tomate", "azeitona"); 
    ...
}

In the line I created an instance of the Pizza class (pizza1) this error message is displayed in the Eclipse IDE:

  

Multiple markers at this line

     
  • Line breakpoint: Main [line: 7] - main (String [])
  •   
  • The Pizza constructor (String, String, String, String) is undefined.
  •   

Would anyone know what could be happening and how can I resolve it?

    
asked by anonymous 10.07.2016 / 13:08

2 answers

5

In order to instantiate the Pizza class in this way declare the second constructor parameter as varargs :

public class Pizza {

    public Pizza (String nomeDestaPizza, String... arrayIngredientes) {

    }
}

The 3 points after String ( String... ) indicates that it is possible to pass an indeterminate number of parameters of type String.

They can be passed through a String Array or multiple Strings separated by commas.

Whatever option you choose they will be stored in an Array (in this case arrayIngredientes ).

So the Pizza class can be instantiated in these two ways:

Form 1:

Pizza pizza1 = new Pizza("americana", "molho de tomate", "mussarela", "presunto", "tomate", "azeitona");

Form 2:

String[] ingredientes = {"molho de tomate", "mussarela", "presunto", "tomate", "azeitona"};
Pizza pizza1 = new Pizza("Americana", ingredientes);
    
10.07.2016 / 15:12
4

You are passing the ingredients as simple objects not as an array. Do it this way:

//você cria o array de Strings
String[] ingredientes = {"molho de tomate", "mussarela", "presunto", "tomate", "azeitona"};
//e depois passa para o construtor da classe
Pizza pizza1 = new Pizza("Americana", ingredientes);
    
10.07.2016 / 13:43