-2

I'm trying to add a string array inside my object.

Here is the code for my object:

    public Question(int id, String question, String[] answers) {
    this.id = id;
    this.question = question;
    this.answers = answers;
}

Here is where I'm having trouble

        questionList.add(
            new Question(
                    1,
                    "This is a question?",

    ));
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Sean Courtney
  • 41
  • 1
  • 7

3 Answers3

1

You could use the String[] literal syntax, like

new String[] { "a", "b", "c" }

or you could rewrite the constructor to take a varargs parameter. Like,

public Question(int id, String question, String... answers) {
    this.id = id;
    this.question = question;
    this.answers = answers;
}

And then you can pass a String[] literal or use comma separated answers (or a String[] literal) to instantiate it.

new Question(
    1,
    "This is a question?",
    "This is an answer.", "This is another answer."
)
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You still need to send in answers as the third param. Also, it's not stated where your define questionList.

To create your 'answers' parameter, one way would be.

String[] answers = new String[]{"Answer 1", "Answer 2"};

You can also convert a list to an array.

String[] answers = Arrays.asList("Answer 1", "Answer 2").toArray(new String[0])
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
0

A string array literal can be written as:

new String[] {"Hellow world", "Bo mundo", "Hola Mundo" }

In declarations you can avoid the 'new String[]' stuff, because java infer the type, but this is not the case. So, if you want to create a new question:

Question question = new Question(1, "2 + 2 = ?", new String[] {"1", "2", "42"});

Anyway, another functionality you could use to reduce such a verbosity is to use '...'. For example, if you write the following instead

public Question(int id, String question, String... answers) {
    this.id = id;
    this.question = question;
    this.answers = answers;
}

answers will still be an array of Strings, but you can call Question's constructors as a variable arguments function:

Question question = new Question(1, "2 + 2 = ?", "1", "2", "42"});

Where all the parameter after question are part of the answers array.