0
public class My {
    float[] arr=new float[]{0.1f,0.2f};

    arr[0]=0.2f;

    public static void main(String []args) {
        My my= new My();
        System.out.println(my.arr[0]);
    }
}

I got errors:

My.java: 4 : error: ']' expected

arr[0]=0.2f;

^
My.java: 4 : error: ';' expected

arr[0]=0.2f;

^

My.java: 4 : error: illegal start of type

arr[0]=0.2f;

^
My.java: 4 : error: <identifier> expected

arr[0]=0.2f;

^

Is there any way to use arr[0]=somevalue; ? Like they do in C?

3
  • 4
    They even don't do that in C outside of functions. Commented Jan 27, 2016 at 11:37
  • Then how should I change the first element in arr? Commented Jan 27, 2016 at 11:40
  • 2
    By doing that in a method. Or in a constructor (not sure if they count as methods). Commented Jan 27, 2016 at 11:40

3 Answers 3

4

You can either fix the initializer of arr to hold the right value from the start

float[] arr=new float[]{0.2f,0.2f};

or you can change your class to change the value inside the constructor:

public class My {
    float[] arr=new float[]{0.1f,0.2f};

    public My() {
        arr[0]=0.2f;
    }

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

Comments

1

Declare array inside a block or function, without using Array as field

public class My{

    public static void main(String[] args) {
        float[] arr = new float[] { 0.1f, 0.2f };
        arr[0] = 0.2f;
        //My my = new My();
        System.out.println(arr[0]);
    }
}

Array as a field using constructor

public class My{

    private float[] arr = null;

    private My() {
        arr = new float[] { 0.1f, 0.2f };
    }

    public static void main(String[] args) {
        My my = new My();
        System.out.println(my.arr[0]);
    }
}

1 Comment

If he needs that as a field of the class, this is not an option.
1

You can fix the initializer of arr value and declare array inside a class.

public class My
{
    public static void main( String[] args )
    {
        My my = new My();
        System.out.println( my.arr[0] );
    }
    private float[] arr = new float[]
                        { 0.1f, 0.2f };
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.