繁体   English   中英

为什么我不能在另一个类中访问我的静态变量

[英]Why cant i access my static variable inside another class

嗨,我对此还很陌生,只掌握了实例和静态变量。我想做的是在内部声明一些东西作为静态变量,并在该类中使用它,并通过用户输入为其分配值,然后使用该输入进行计算,然后将此输入发送到另一个类(没有main方法)中,并在数组中使用它。 可能吗 ? 如果可以的话如何? 从我的方式来看,它说无法识别变量,所以很明显我是错的。我知道我可以使用setter和getter来做到这一点,但我不知道该怎么做。在此先感谢您。远

  public class Character {

       public static int amount =0;

       public void calculate(){

       amount=sc.nextInt();

       if(amount<0){
                 System.out.print("You are broke");
                       }
        else{
              System.out.print("You are ok You have"+amount);
            }
  }

在另一个班级内,我想使用此金额

public class calculation2{

    int [] arr=new int[amount];

    public void smile(){

      bla bla bla bla

     }
}

我该怎么办?我在做什么方面有错,有什么建议可以解决? 太谢谢你了

由于它是静态的,因此您可以通过以下方式在calculation2中引用静态量变量:

int [] arr=new int[Character.amount];

public void smile(){

  System.out.println(Character.amount);

 }

尽管您不应该这样编写代码。 当某个东西具有实际值或返回值并且您想在另一个类中使用它时,请使用static。

这不是正确的编码方式:但是,在代码中,您已将static变量声明为amount作为public,因此可以在smile方法中访问它,如下所示:

int [] arr=new int[Character.amount];    
public void smile(){
      System.out.println(Character.amount);
     }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM