Constructor with a String and a String array is not working

Asked

Viewed 567 times

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

On 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:Home [line: 7] - main(String[])
  • The constructor Pizza(String, String, String, String) is Undefined.

Someone would know what’s going on and how to fix it?

2 answers

5

To instantiate the class Pizza thus declares the second parameter of the constructor 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 undetermined number of parameters of type String.

They can be passed through a String Array or several Strings comma-separated.

Whichever option is chosen they will be stored in a Array(in this case arrayIngredientes).

Thus, the class Pizza 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);

4

You are passing the ingredients as simple objects not as array. Do it that 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);

Browser other questions tagged

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