打算写一个从文件读数据,并保存在GPSdata类中。环境:jdk1.6
错误提示是:
    non-static variable this cannot be referenced from a static context
                                                                                  g[i]=new GPSdata();
                                                                                          ^             
啥意思……?请各位高手赐教。程序是我改书上的,运行原程序没问题,为啥我改了,就报这个错。
程序如下:
……
主程序
public static void main(String[] args) {
 
try{
// Retrive the data from ".txt" file
BufferedReader in=new BufferedReader(new FileReader("JB+XJT.TXT"));
GPSdata[] gdata=readData(in);
in.close();

//print for testing
for(int i=0;i<gdata.length;i++)
System.out.println(gdata[i]);

}catch(IOException exception)
{
exception.printStackTrace();
} }
从文件读入数据并赋给GPSdata数组:
static GPSdata[] readData(BufferedReader in) throws IOException
{
//retrieve the array size
int n=Integer.parseInt(in.readLine());

GPSdata[] g=new GPSdata[n];
for(int i=0;i<n;i++)
{
g[i]=new GPSdata();
g[i].readData(in);
}
return g;
}
GPSdata类:
class GPSdata
{
public GPSdata() {};

public GPSdata(String t,double h,double v)
{
utc=t;
latitude=h;
longitude=v;
}

public String getUTC()
{
return utc;
}

public double getLatitude()
{
return latitude;
}

public double getLongitude()
{
return longitude;
}

public void readData(BufferedReader in) throws IOException
{
String d=in.readLine();
StringTokenizer t=new StringTokenizer(d,"(,)");
utc=t.nextToken();
longitude=Double.parseDouble(t.nextToken());
latitude=Double.parseDouble(t.nextToken());
}
private double latitude;
private double longitude;
private String utc;
}

解决方案 »

  1.   

    GPSdata 类是main方法的内部类吗??如果不是的话 你在class GPSdata的上面少写了个大括号。。加上就好了。要是内部类的话你的语法有错误
    用 g[i] = new TestA().new GPSdata(); 
      

  2.   

    static GPSdata[] 这个是静态方法,是不需要类实例化就能调用得 里面是不能调用非静态得变量或方法得  内部类也算是这个类得一个成员 故不能调用
      

  3.   


    3楼朋友理解错误了吧!楼主是在一个类中,只把类中的方法和内部类贴了出来,所以应该不存在少大括号的问题楼主准备:从文件读数据,并保存在GPSdata类中,出现上面错误:非静态变量无法引用静态变量的的,因为
    static GPSdata[] readData(BufferedReader in) throws IOException 你返回的静态GPSdata[]类型变量,
    而你的GPSdata内部类是public的,系统会人认为你的GPSdata[]类型的变量g中的数组元素在readData()方法中
    已经初始化过了,你尝试把static去掉试一下
      

  4.   

    谢谢~!
    两位高手赐教~!小女,忘了把GPSdata类与主类分开了……
    最后,挥泪三分感谢大侠……