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

标签 java

    public static void main(String[] args) {

        Player Anfallare = new Player("A");
        Player Forsvarare = new Player("F");
        MotVarandra(Anfallare.getDice(1), Forsvarare.getDice(1));
    (...)
   }

是我的main函数,现在我做了一个自己的函数,

public static void MotVarandra(int a, int f){
    if(f >= a){
        Anfallare.armees-=1;
    }else{
        Forsvarare.armees-=1;
    }
}

应该将对象的变量设置为 -=1.. 但这不起作用,因为该函数不知道 Anfallare 和 Forsvarare 是一个对象..

在这种情况下我能做什么?

最佳答案

您需要将 Player 定义为类字段,而不是在 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;
    }
  }
}

关于Java:在外部函数中设置对象变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6128198/

相关文章:

java - 从已编译的项目重建java项目

java - "Endless"来自套接字的 AudioInputStream

java - 从 Wildfly 13 发送消息到远程 Artemis ActiveMQ

java - 整个项目分成不同的模块时如何避免依赖问题

java - 如何使用 Maven 使用 Selenium 3.4.0 启动 FireFoxDriver?

java - 向多个收件人发送邮件

java - REST 客户端调用失败并显示 "SunCertPathBuilderException: unable to find valid certification path to requested target"

java - 在 fragment 生命周期中跟踪对象实例

java - 如何将 SVN 项目作为 Java 项目 checkout 到 Eclipse 中?

java - 执行环境描述、标准 1.1x VM 和标准 VM 之间有什么区别