Java:在外部函数中设置对象变量

问题描述

|
    public static void main(String[] args) {

        Player Anfallare = new Player(\"A\");
        Player Forsvarare = new Player(\"F\");
        MotVarandra(Anfallare.getDice(1),Forsvarare.getDice(1));
    (...)
   }
这是我的主要功能,现在我做了一个自己的功能,
public static void MotVarandra(int a,int f){
    if(f >= a){
        Anfallare.armees-=1;
    }else{
        Forsvarare.armees-=1;
    }
}
应该将对象的变量设置为-= 1。但这不起作用,因为该函数不知道Anfallare和Forsvarare是对象。 在这种情况下我该怎么办?     

解决方法

您需要将“ 2”定义为类字段,而不是在main方法内部。 有关Java的简要介绍,建议您从这里开始阅读: http://download.oracle.com/javase/tutorial/java/index.html 另外,这里有很多不错的书建议:https://stackoverflow.com/questions/75102/best-java-book-you-have-read-so-far。这些书中有些很好,可以开始学习。 这里的例子:
public class Game {
  private static Player Anfallare,Forsvarare; //  <-- you define them here,so they are available to any method in the class

  public static void main(String[] args) {

    Anfallare = new Player(\"A\");  //  <-- it is already defined as a Player,so now you only need to instantiate it
    Forsvarare = new Player(\"F\");
    MotVarandra(Anfallare.getDice(1),Forsvarare.getDice(1));
    // ...
  }
  public static void MotVarandra(int a,int f){
    if(f >= a){
        Anfallare.armees-=1; //  <-- it is already defined and instantiated
    }else{
        Forsvarare.armees-=1;
    }
  }
}
    ,尽管到目前为止,Aleadam的解决方案是最好的答案,但是要专门解决此问题,您可以做的另一件事是更改函数的参数:
public static void MotVarandra(Player a,Player f){
    if(f.getDice(1) >= a.getDice(1)){
        f.armees-=1;
    }else{
        a.armees-=1;
    }
}
最终,您的最佳解决方案仅取决于您的程序在做什么。很有可能,这只是另一种查看方式。 附带说明一下,请确保使用描述性命名技术,a和f进行了一定程度的硬编码,并且仅在您的播放器仅使用这些变量名称时才有意义。最好不要潜在地限制您的代码。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...