日期:2014-05-20  浏览次数:20690 次

//急急急,关于数组的一个小问题,等待解决.
//不知道为什么,编译不能通过
public   class   Temp
{
int   arr[]=new   int[30];
arr[1]=100;
public   static   void   main(String   args[])
{
System.out.println(arr[1]);
}
}


------解决方案--------------------
public class Temp
{
static int arr[]=new int[30];

public static void main(String args[])
{
arr[1]=100;
System.out.println(arr[1]);
}
}


------解决方案--------------------

------解决方案--------------------
你有两个错误,

第一个arr[1]=100;应该出现在一个方法中,因为它是一条单独的赋值语句,跟int i=0;是不一样的,int i=0;是给变量一个初始化的值,而你的是作为一句单独的语句是不行的。
就像
public class Temp
{
int i=0;
arr[1]=100;
public static void main(String args[])
{
}
}

可以,但是
public class Temp
{
int i;
i=0;
arr[1]=100;
public static void main(String args[])
{
}
}
却不可以,因为i=0;出现在了声明的部分。


第二个错误


System.out.println(arr[1]);


因为你的arr声明是个非static的,所以它是不能在static方法中被引用的。
------解决方案--------------------
在java的类体中,只有变量的定义与方法的定义。
------解决方案--------------------
我相信随便找个ide都可以提示LZ的错误的,lz本身对类的概念没有理解好
------解决方案--------------------
把数组定义成static就可以了
------解决方案--------------------
把数组定成静态的且把赋值语句写入方法里面;
或者把数组定义跟赋值语句都写在方法里面
------解决方案--------------------
除了初始化赋值外,其他的赋值语句必须包含在方法里面
[http://www.willwell.cn]
------解决方案--------------------
因为你的arr声明是个非static的,所以它是不能在static方法中被引用的。