昨天在学习java.lang.string的API的时候,突然想知道offsetByCodePoints返回的值是什么样子,就编了如下代码,结果出了问题,说不能在静态上下文中引用非静态变量,我想问一下为什么造成这种情况,还有该如何改正
class test{
  String s="helloeveryone";
  int h=s.offsetByCodePoints(0,5);
  public static void main(String[] args){
    System.out.println(h);
}
}

解决方案 »

  1.   

    class   Test{
        static String   s= "helloeveryone ";
        static int   h=s.offsetByCodePoints(0,5);
        public   static   void   main(String[]   args){
            System.out.println(h);
    }
    }说的都挺明确的了  静态方法只能引用静态变量
      

  2.   

    h是类中非静态变量,只能通过对象来访问。
    请改为如下,或者将h设为静态变量。        System.out.println(new Test().h); 
      

  3.   

    class   test{ 
       static String   s= "helloeveryone "; 
        static int   h=s.offsetByCodePoints(0,5); 
        public   static   void   main(String[]   args){ 
            System.out.println(h); 

    }
    或者class   test{ 
        String   s= "helloeveryone "; 
        int   h=s.offsetByCodePoints(0,5); 
        public   static   void   main(String[]   args){ 
            test t = new test();
            System.out.println(t.h); 

    }
      

  4.   

    道理很简单
    首先要知道:
    静态变量、方法也叫类变量、方法,属于类。它在类被load时就已经存在了,用类名都可直接访问。
    一般变量属于具体对象,不属于类层次的,必须用对象来引用。然后:
    可以从上面知道,静态变量或方法在没有对象的情况下就存在了,不管此时有没有创建对象。而一般变量在没有对象的情况下并不会被创建,也就是还不存在。那么用已经存在的类方法去调用还没被创建的一般变量当然是不允许的!关于静态可以举个例子
    class test4
    {
        public static void main(String s[])
        { 
           test4 qq = new test4();
           qq.fun();
        }
        static{
             System.out.println("2");
        }
        void fun(){
             System.out.println("1");
        }    
    }
    你看看谁会被先打印出来