2016-04-16 45 views
-3

我写下了一个简单的程序来演示静态关键字的使用。我还输入了一个方法来计算变量的平方,并初始化了主类中静态变量的值。如何将静态变量的值传递给方法?

class staticdemo{ 
public static int stvar; 

void square(int stvar){ 
    System.out.println("" + stvar*stvar); 
} 

} 
public class statictest { 
public static void main(String args[]){ 
    staticdemo.stvar = 10; 
int s = staticdemo.stvar; 
    square(s); //HERE IS WHERE I GET THE ERROR! 
} 
} 

确切的错误我得到的是“法方(INT)是未定义statictest类型”

我怎样才能用一个静态变量执行的方法是什么?

+0

__JavaScript__ ??? – Rayon

+0

用正确的代码标签标记问题,你会得到一些答案。这不是Javascript。 – Dominofoe

+0

应该是'staticdemo.square'而不是'square'。我投票结束这个低质量的问题。 – Everv0id

回答

0

的问题不在于你传递一个静态字段(不变量)到方法。这就是你正试图调用一个没有实例的实例方法。

或者:

  1. squarestatic为好,这样你就可以从main调用它,或

  2. main创建一个实例来调用它:

    new staticdemo().square(staticdemo.stvar); 
    

我也强烈推荐您不要为静态字段(stvar)和功能参数(square中的stvar)使用相同的名称。这只是要求混乱和麻烦。

还建议遵循标准的Java命名约定,即使在您自己的测试代码中,但特别是在向他人请求帮助时。

因此,或许:

class StaticDemo { 
    public static int stvar; 

    public static void square(int s) { 
    //  ^^^^^^    ^
     System.out.println("" + s * s); 
    //      ^^
    } 
} 

public class StaticTest { 
    public static void main(String args[]) { 
     StaticDemo.square(StaticDemo.stvar); 
    // ^^^^^^^^^^^  ^^^^^^^^^^^^^^^^ 
    } 
} 

或者交替:

class StaticDemo { 
    public static int stvar; 

    public void square(int s) { 
    //     ^
     System.out.println("" + s * s); 
    //      ^^
    } 
} 

public class StaticTest { 
    public static void main(String args[]) { 
     new StaticDemo().square(StaticDemo.stvar); 
    // ^^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^ 
    } 
} 
0

你的方法也应该是静态的

0

这个方法必须是静态的

void square(int stvar),如果你想从一个静态的背景下

称之为另一个更优雅和OOP方式是通过声明为私有声明一个类的对象,封装及其成员

public static void main(String args[]){ 
    staticdemo.stvar = 10; 
    int s = staticdemo.stvar; 
    staticdemo foo = new staticdemo(); 

    foo.square(s); //HERE will work fine! 
} 
0

你不能直接调用非静态方法。你必须为staticdemo类创建一个对象,然后你可以使用oobject调用该方法。 主要方法里面输入 staticdemo st = new staticdemo(); st.square(s);