3

I'm trying to make some test data with which to test some functionality of my code. To this end, I need a double[][]. I am trying to do with a function that takes a double[][] as an input parameter and copying onto it a local variable containing the test data. However, I get an error that I don't quite understand (I'm sure it's a very basic error, which is why I'm unable to Google it), understanding/fixing which I'd appreciate any help.

private void makeData(double[][] patterns)
{
    double[][] data = new double[2][];
    // exists so that I can change `data` easily, without having to change the core functionality of copying it over to `patterns`
    data[0] = {1.0,8.0}; // error!
    // copy over everything from data into patterns
}

The line marked in the above code is giving me the error Only assignment, call, increment, decrement, and new objects can be used as a statement. To this, my reaction is "Isn't data[0] = {1.0,8.0}; an assignment?

I'm fairly confused, so I'd appreciate any help

3
  • 1
    you're using a 2 dimensional array and your second statement became 1 dimensional array Commented Jul 22, 2013 at 14:25
  • new double[]{,} (I presume the data type is required) Commented Jul 22, 2013 at 14:25
  • @rajeem_cariazo: Thank you. That is exactly the explanation that I needed Commented Jul 22, 2013 at 14:26

3 Answers 3

5

You want to do

data[0] = new[] {1.0, 8.0};

The curly brace initializers are only valid if you're creating an object/array. They don't work by themselves.

You can specify the type specifically:

data[0] = new double[] {1.0, 8.0};

But you don't have to if the compiler can infer the right type (which, in your case, it can).

Sign up to request clarification or add additional context in comments.

Comments

3

Just replace:

data[0] = {1.0,8.0};

by:

data[0] = new double[] { 1.0, 8.0 };

The compiler has to know explicitly what to assign to data[0]. It doesn't infer it from the type of data[0].

3 Comments

You can actually type new[] {...} because it can infer the type from the contents of the initializer.
I never do it for numbers because its easy to get lost with integers, floats, doubles, etc. And the type is infered, not from the type of data[0], but from the content of the initializer.
Yes, I said that it would infer the type based on the contents of the array. Note that if it inferred the wrong type then it wouldn't compile; if, for example, the contents were of type int and it made it an int[] then you'd get an error assigning that to a double[], so the code would remain clear in context.
1

You should to initialize your subarray first.

double[][] data = new double[2][];
data[0] = new double[] {1.0f, 8.0f};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.