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/