0

I am new to java and trying to learn array in java, so when i executed this

class Example
{
    int [] i= new int[2];
    i[0]=5;    //error in this line. Trying to assign 5 to 1st position of array i.

    void m1()
    {
        System.out.println("i[0]:"+i);
    }

    public static void main(String args[])
    {
        Example a=new Example();
        a.m1();
    }
}

it gives error as ']' expected on line number 4 here.

I know within function it will work only want to know why not like this and is there any solution and if not what is the reason?

Sorry, didn't copy but wrote the program incorrectly...Now its the correct one.

4

2 回答 2

3
int[0] = 5;

是错的。你应该使用

i[0] = 5;

但是你不能在课堂上做这样的作业。您必须在方法中移动该声明,或者在数组声明中执行以下操作:

int[] i= {5};//same as int[] i = new int[1]; i[0] = 5;
于 2013-09-16T19:57:57.580 回答
2

This line is incorrect:

int[0] = 5;

You meant this (notice the block, and the correct name of the array):

{
    i[0] = 5;
}

Or you could declare an initialize the array in a single line:

int[] i = {5};

Also notice that as a convention, the [] part is usually written after the type of the array, not after the name of the array (that's a C convention, not a Java convention).

于 2013-09-16T19:58:42.110 回答