2011-05-25 47 views
1
public static void main(String[] args) { 

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

是我的主要功能,现在我做了一个自己的功能,的Java:设置对象在外面函数的变量

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

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

我可以在这种情况下怎么办?

回答

5

您需要定义Player S作为类字段,而不是主方法中。

一个温柔的介绍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; 
    } 
    } 
} 
+0

在学校,我试着做一个自己的小项目的比赛,但感谢链接尽管可能你也许指定有关如何定义,而不是在里面的主要球员类领域的其他链接更详细的进出口学习Java的? – Karem 2011-05-25 17:16:24

+0

@Karem从oracle链接,按照“语言基础”和“类和对象”。这将比仅仅是一个例子更有帮助。无论如何,我添加了这个例子,所以你知道我在说什么。 – Aleadam 2011-05-25 17:19:42

+0

顺便说一句,如果你需要访问类外的球员表格,你需要像弗雷德里克说的那样将'private'改为'public'或创建一组“getter”和“setter”。 – Aleadam 2011-05-25 17:22:08

2

虽然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都有点硬编码,且仅当您使用只为你的球员的变量名是有意义的。最好不要限制你的代码。

+0

+1总有不止一种方法可以做任何事情 – Aleadam 2011-05-25 17:48:53