How to modify all array elements in 1 line?

ei1ei1
edited January 2016 in Questions about Code

float[] point; point = {2, 3};
How does one do this?
Do you really have to define elements individually?

Answers

  • edited January 2016 Answer ✓
    float[] point = {2, 3};
    

    You can do that. If you want to change them all later, you will have to loop and change the values:

    for(int i=0;i<point.length;i++) point[i] = i;
    

    Or, since it looks like you're using an array to do a point, consider using a PVector:

    PVector p = new PVector(2,3);
    p.x = 0;
    p.y = 1;
    

    I would avoid using "point" as the name of a variable; it can be confusing.

  • ei1ei1
    edited January 2016

    But how do you do stuff that a loop cannot do?
    float[] notPoint; notPoint = {0.2, 1.5, -500, 67, 3.1415};

  • edited January 2016 Answer ✓

    Java only allows array instantiations w/ just curly braces when we're also declaring the variable to hold its reference at the same time;

    float[] notPoint = { .2, 1.5, -500, 67, PI };
    

    Otherwise, we're gonna need to specify the type before the curly braces as well:

    float[] notPoint;
    notPoint = new float[] { .2, 1.5, -500, 67, PI };
    
Sign In or Register to comment.